gmain: use GPrivate instead of GStaticPrivate
[platform/upstream/glib.git] / glib / gmain.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * gmain.c: Main loop abstraction, timeouts, and idle functions
5  * Copyright 1998 Owen Taylor
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20  * Boston, MA 02111-1307, USA.
21  */
22
23 /*
24  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GLib Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GLib at ftp://ftp.gtk.org/pub/gtk/.
28  */
29
30 /*
31  * MT safe
32  */
33
34 #include "config.h"
35 #include "glibconfig.h"
36
37 /* Uncomment the next line (and the corresponding line in gpoll.c) to
38  * enable debugging printouts if the environment variable
39  * G_MAIN_POLL_DEBUG is set to some value.
40  */
41 /* #define G_MAIN_POLL_DEBUG */
42
43 #ifdef _WIN32
44 /* Always enable debugging printout on Windows, as it is more often
45  * needed there...
46  */
47 #define G_MAIN_POLL_DEBUG
48 #endif
49
50 #ifdef G_OS_UNIX
51 #include "glib-unix.h"
52 #include <pthread.h>
53 #ifdef HAVE_EVENTFD
54 #include <sys/eventfd.h>
55 #endif
56 #endif
57
58 #include <signal.h>
59 #include <sys/types.h>
60 #include <time.h>
61 #include <stdlib.h>
62 #ifdef HAVE_SYS_TIME_H
63 #include <sys/time.h>
64 #endif /* HAVE_SYS_TIME_H */
65 #ifdef HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif /* HAVE_UNISTD_H */
68 #include <errno.h>
69 #include <string.h>
70
71 #ifdef G_OS_WIN32
72 #define STRICT
73 #include <windows.h>
74 #endif /* G_OS_WIN32 */
75
76 #ifdef G_OS_BEOS
77 #include <sys/socket.h>
78 #include <sys/wait.h>
79 #endif /* G_OS_BEOS */
80
81 #include "gmain.h"
82
83 #include "garray.h"
84 #include "giochannel.h"
85 #include "ghash.h"
86 #include "ghook.h"
87 #include "gqueue.h"
88 #include "gstrfuncs.h"
89 #include "gtestutils.h"
90
91 #ifdef G_OS_WIN32
92 #include "gwin32.h"
93 #endif
94
95 #ifdef  G_MAIN_POLL_DEBUG
96 #include "gtimer.h"
97 #endif
98
99 #include "gwakeup.h"
100
101 #include "glib-private.h"
102
103 /**
104  * SECTION:main
105  * @title: The Main Event Loop
106  * @short_description: manages all available sources of events
107  *
108  * The main event loop manages all the available sources of events for
109  * GLib and GTK+ applications. These events can come from any number of
110  * different types of sources such as file descriptors (plain files,
111  * pipes or sockets) and timeouts. New types of event sources can also
112  * be added using g_source_attach().
113  *
114  * To allow multiple independent sets of sources to be handled in
115  * different threads, each source is associated with a #GMainContext.
116  * A GMainContext can only be running in a single thread, but
117  * sources can be added to it and removed from it from other threads.
118  *
119  * Each event source is assigned a priority. The default priority,
120  * #G_PRIORITY_DEFAULT, is 0. Values less than 0 denote higher priorities.
121  * Values greater than 0 denote lower priorities. Events from high priority
122  * sources are always processed before events from lower priority sources.
123  *
124  * Idle functions can also be added, and assigned a priority. These will
125  * be run whenever no events with a higher priority are ready to be processed.
126  *
127  * The #GMainLoop data type represents a main event loop. A GMainLoop is
128  * created with g_main_loop_new(). After adding the initial event sources,
129  * g_main_loop_run() is called. This continuously checks for new events from
130  * each of the event sources and dispatches them. Finally, the processing of
131  * an event from one of the sources leads to a call to g_main_loop_quit() to
132  * exit the main loop, and g_main_loop_run() returns.
133  *
134  * It is possible to create new instances of #GMainLoop recursively.
135  * This is often used in GTK+ applications when showing modal dialog
136  * boxes. Note that event sources are associated with a particular
137  * #GMainContext, and will be checked and dispatched for all main
138  * loops associated with that GMainContext.
139  *
140  * GTK+ contains wrappers of some of these functions, e.g. gtk_main(),
141  * gtk_main_quit() and gtk_events_pending().
142  *
143  * <refsect2><title>Creating new source types</title>
144  * <para>One of the unusual features of the #GMainLoop functionality
145  * is that new types of event source can be created and used in
146  * addition to the builtin type of event source. A new event source
147  * type is used for handling GDK events. A new source type is created
148  * by <firstterm>deriving</firstterm> from the #GSource structure.
149  * The derived type of source is represented by a structure that has
150  * the #GSource structure as a first element, and other elements specific
151  * to the new source type. To create an instance of the new source type,
152  * call g_source_new() passing in the size of the derived structure and
153  * a table of functions. These #GSourceFuncs determine the behavior of
154  * the new source type.</para>
155  * <para>New source types basically interact with the main context
156  * in two ways. Their prepare function in #GSourceFuncs can set a timeout
157  * to determine the maximum amount of time that the main loop will sleep
158  * before checking the source again. In addition, or as well, the source
159  * can add file descriptors to the set that the main context checks using
160  * g_source_add_poll().</para>
161  * </refsect2>
162  * <refsect2><title>Customizing the main loop iteration</title>
163  * <para>Single iterations of a #GMainContext can be run with
164  * g_main_context_iteration(). In some cases, more detailed control
165  * of exactly how the details of the main loop work is desired, for
166  * instance, when integrating the #GMainLoop with an external main loop.
167  * In such cases, you can call the component functions of
168  * g_main_context_iteration() directly. These functions are
169  * g_main_context_prepare(), g_main_context_query(),
170  * g_main_context_check() and g_main_context_dispatch().</para>
171  * <para>The operation of these functions can best be seen in terms
172  * of a state diagram, as shown in <xref linkend="mainloop-states"/>.</para>
173  * <figure id="mainloop-states"><title>States of a Main Context</title>
174  * <graphic fileref="mainloop-states.gif" format="GIF"></graphic>
175  * </figure>
176  * </refsect2>
177  *
178  * On Unix, the GLib mainloop is incompatible with fork().  Any program
179  * using the mainloop must either exec() or exit() from the child
180  * without returning to the mainloop.
181  */
182
183 /* Types */
184
185 typedef struct _GTimeoutSource GTimeoutSource;
186 typedef struct _GChildWatchSource GChildWatchSource;
187 typedef struct _GUnixSignalWatchSource GUnixSignalWatchSource;
188 typedef struct _GPollRec GPollRec;
189 typedef struct _GSourceCallback GSourceCallback;
190
191 typedef enum
192 {
193   G_SOURCE_READY = 1 << G_HOOK_FLAG_USER_SHIFT,
194   G_SOURCE_CAN_RECURSE = 1 << (G_HOOK_FLAG_USER_SHIFT + 1)
195 } GSourceFlags;
196
197 typedef struct _GMainWaiter GMainWaiter;
198
199 struct _GMainWaiter
200 {
201   GCond *cond;
202   GMutex *mutex;
203 };
204
205 typedef struct _GMainDispatch GMainDispatch;
206
207 struct _GMainDispatch
208 {
209   gint depth;
210   GSList *dispatching_sources; /* stack of current sources */
211 };
212
213 #ifdef G_MAIN_POLL_DEBUG
214 gboolean _g_main_poll_debug = FALSE;
215 #endif
216
217 struct _GMainContext
218 {
219   /* The following lock is used for both the list of sources
220    * and the list of poll records
221    */
222   GMutex mutex;
223   GCond cond;
224   GThread *owner;
225   guint owner_count;
226   GSList *waiters;
227
228   gint ref_count;
229
230   GPtrArray *pending_dispatches;
231   gint timeout;                 /* Timeout for current iteration */
232
233   guint next_id;
234   GSource *source_list;
235   gint in_check_or_prepare;
236
237   GPollRec *poll_records, *poll_records_tail;
238   guint n_poll_records;
239   GPollFD *cached_poll_array;
240   guint cached_poll_array_size;
241
242   GWakeup *wakeup;
243
244   GPollFD wake_up_rec;
245
246 /* Flag indicating whether the set of fd's changed during a poll */
247   gboolean poll_changed;
248
249   GPollFunc poll_func;
250
251   gint64   time;
252   gboolean time_is_fresh;
253 };
254
255 struct _GSourceCallback
256 {
257   guint ref_count;
258   GSourceFunc func;
259   gpointer    data;
260   GDestroyNotify notify;
261 };
262
263 struct _GMainLoop
264 {
265   GMainContext *context;
266   gboolean is_running;
267   gint ref_count;
268 };
269
270 struct _GTimeoutSource
271 {
272   GSource     source;
273   gint64      expiration;
274   guint       interval;
275   gboolean    seconds;
276 };
277
278 struct _GChildWatchSource
279 {
280   GSource     source;
281   GPid        pid;
282   gint        child_status;
283 #ifdef G_OS_WIN32
284   GPollFD     poll;
285 #else /* G_OS_WIN32 */
286   gboolean    child_exited;
287 #endif /* G_OS_WIN32 */
288 };
289
290 struct _GUnixSignalWatchSource
291 {
292   GSource     source;
293   int         signum;
294   gboolean    pending;
295 };
296
297 struct _GPollRec
298 {
299   GPollFD *fd;
300   GPollRec *prev;
301   GPollRec *next;
302   gint priority;
303 };
304
305 struct _GSourcePrivate
306 {
307   GSList *child_sources;
308   GSource *parent_source;
309 };
310
311 #define LOCK_CONTEXT(context) g_mutex_lock (&context->mutex)
312 #define UNLOCK_CONTEXT(context) g_mutex_unlock (&context->mutex)
313 #define G_THREAD_SELF g_thread_self ()
314
315 #define SOURCE_DESTROYED(source) (((source)->flags & G_HOOK_FLAG_ACTIVE) == 0)
316 #define SOURCE_BLOCKED(source) (((source)->flags & G_HOOK_FLAG_IN_CALL) != 0 && \
317                                 ((source)->flags & G_SOURCE_CAN_RECURSE) == 0)
318
319 #define SOURCE_UNREF(source, context)                       \
320    G_STMT_START {                                           \
321     if ((source)->ref_count > 1)                            \
322       (source)->ref_count--;                                \
323     else                                                    \
324       g_source_unref_internal ((source), (context), TRUE);  \
325    } G_STMT_END
326
327
328 /* Forward declarations */
329
330 static void g_source_unref_internal             (GSource      *source,
331                                                  GMainContext *context,
332                                                  gboolean      have_lock);
333 static void g_source_destroy_internal           (GSource      *source,
334                                                  GMainContext *context,
335                                                  gboolean      have_lock);
336 static void g_source_set_priority_unlocked      (GSource      *source,
337                                                  GMainContext *context,
338                                                  gint          priority);
339 static void g_main_context_poll                 (GMainContext *context,
340                                                  gint          timeout,
341                                                  gint          priority,
342                                                  GPollFD      *fds,
343                                                  gint          n_fds);
344 static void g_main_context_add_poll_unlocked    (GMainContext *context,
345                                                  gint          priority,
346                                                  GPollFD      *fd);
347 static void g_main_context_remove_poll_unlocked (GMainContext *context,
348                                                  GPollFD      *fd);
349
350 static gboolean g_timeout_prepare  (GSource     *source,
351                                     gint        *timeout);
352 static gboolean g_timeout_check    (GSource     *source);
353 static gboolean g_timeout_dispatch (GSource     *source,
354                                     GSourceFunc  callback,
355                                     gpointer     user_data);
356 static gboolean g_child_watch_prepare  (GSource     *source,
357                                         gint        *timeout);
358 static gboolean g_child_watch_check    (GSource     *source);
359 static gboolean g_child_watch_dispatch (GSource     *source,
360                                         GSourceFunc  callback,
361                                         gpointer     user_data);
362 static void     g_child_watch_finalize (GSource     *source);
363 #ifdef G_OS_UNIX
364 static void g_unix_signal_handler (int signum);
365 static gboolean g_unix_signal_watch_prepare  (GSource     *source,
366                                               gint        *timeout);
367 static gboolean g_unix_signal_watch_check    (GSource     *source);
368 static gboolean g_unix_signal_watch_dispatch (GSource     *source,
369                                               GSourceFunc  callback,
370                                               gpointer     user_data);
371 static void     g_unix_signal_watch_finalize  (GSource     *source);
372 #endif
373 static gboolean g_idle_prepare     (GSource     *source,
374                                     gint        *timeout);
375 static gboolean g_idle_check       (GSource     *source);
376 static gboolean g_idle_dispatch    (GSource     *source,
377                                     GSourceFunc  callback,
378                                     gpointer     user_data);
379
380 static GMainContext *glib_worker_context;
381 static gboolean      g_main_context_fork_detected;
382
383 G_LOCK_DEFINE_STATIC (main_loop);
384 static GMainContext *default_main_context;
385
386 #ifndef G_OS_WIN32
387
388
389 /* UNIX signals work by marking one of these variables then waking the
390  * worker context to check on them and dispatch accordingly.
391  */
392 static volatile gchar unix_signal_pending[NSIG];
393 static volatile gboolean any_unix_signal_pending;
394
395 /* Guards all the data below */
396 G_LOCK_DEFINE_STATIC (unix_signal_lock);
397 static GSList *unix_signal_watches;
398 static GSList *unix_child_watches;
399
400 static GSourceFuncs g_unix_signal_funcs =
401 {
402   g_unix_signal_watch_prepare,
403   g_unix_signal_watch_check,
404   g_unix_signal_watch_dispatch,
405   g_unix_signal_watch_finalize
406 };
407 #endif /* !G_OS_WIN32 */
408 G_LOCK_DEFINE_STATIC (main_context_list);
409 static GSList *main_context_list = NULL;
410
411 GSourceFuncs g_timeout_funcs =
412 {
413   g_timeout_prepare,
414   g_timeout_check,
415   g_timeout_dispatch,
416   NULL
417 };
418
419 GSourceFuncs g_child_watch_funcs =
420 {
421   g_child_watch_prepare,
422   g_child_watch_check,
423   g_child_watch_dispatch,
424   g_child_watch_finalize
425 };
426
427 GSourceFuncs g_idle_funcs =
428 {
429   g_idle_prepare,
430   g_idle_check,
431   g_idle_dispatch,
432   NULL
433 };
434
435 /**
436  * g_main_context_ref:
437  * @context: a #GMainContext
438  * 
439  * Increases the reference count on a #GMainContext object by one.
440  *
441  * Returns: the @context that was passed in (since 2.6)
442  **/
443 GMainContext *
444 g_main_context_ref (GMainContext *context)
445 {
446   g_return_val_if_fail (context != NULL, NULL);
447   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL); 
448
449   g_atomic_int_inc (&context->ref_count);
450
451   return context;
452 }
453
454 static inline void
455 poll_rec_list_free (GMainContext *context,
456                     GPollRec     *list)
457 {
458   g_slice_free_chain (GPollRec, list, next);
459 }
460
461 /**
462  * g_main_context_unref:
463  * @context: a #GMainContext
464  * 
465  * Decreases the reference count on a #GMainContext object by one. If
466  * the result is zero, free the context and free all associated memory.
467  **/
468 void
469 g_main_context_unref (GMainContext *context)
470 {
471   GSource *source;
472   g_return_if_fail (context != NULL);
473   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0); 
474
475   if (!g_atomic_int_dec_and_test (&context->ref_count))
476     return;
477
478   G_LOCK (main_context_list);
479   main_context_list = g_slist_remove (main_context_list, context);
480   G_UNLOCK (main_context_list);
481
482   source = context->source_list;
483   while (source)
484     {
485       GSource *next = source->next;
486       g_source_destroy_internal (source, context, FALSE);
487       source = next;
488     }
489
490   g_mutex_clear (&context->mutex);
491
492   g_ptr_array_free (context->pending_dispatches, TRUE);
493   g_free (context->cached_poll_array);
494
495   poll_rec_list_free (context, context->poll_records);
496
497   g_wakeup_free (context->wakeup);
498   g_cond_clear (&context->cond);
499
500   g_free (context);
501 }
502
503 #ifdef G_OS_UNIX
504 static void
505 g_main_context_forked (void)
506 {
507   g_main_context_fork_detected = TRUE;
508 }
509 #endif
510
511 /**
512  * g_main_context_new:
513  * 
514  * Creates a new #GMainContext structure.
515  * 
516  * Return value: the new #GMainContext
517  **/
518 GMainContext *
519 g_main_context_new (void)
520 {
521   static gsize initialised;
522   GMainContext *context;
523
524   if (g_once_init_enter (&initialised))
525     {
526 #ifdef G_MAIN_POLL_DEBUG
527       if (getenv ("G_MAIN_POLL_DEBUG") != NULL)
528         _g_main_poll_debug = TRUE;
529 #endif
530
531 #ifdef G_OS_UNIX
532       pthread_atfork (NULL, NULL, g_main_context_forked);
533 #endif
534
535       g_once_init_leave (&initialised, TRUE);
536     }
537
538   context = g_new0 (GMainContext, 1);
539
540   g_mutex_init (&context->mutex);
541   g_cond_init (&context->cond);
542
543   context->owner = NULL;
544   context->waiters = NULL;
545
546   context->ref_count = 1;
547
548   context->next_id = 1;
549   
550   context->source_list = NULL;
551   
552   context->poll_func = g_poll;
553   
554   context->cached_poll_array = NULL;
555   context->cached_poll_array_size = 0;
556   
557   context->pending_dispatches = g_ptr_array_new ();
558   
559   context->time_is_fresh = FALSE;
560   
561   context->wakeup = g_wakeup_new ();
562   g_wakeup_get_pollfd (context->wakeup, &context->wake_up_rec);
563   g_main_context_add_poll_unlocked (context, 0, &context->wake_up_rec);
564
565   G_LOCK (main_context_list);
566   main_context_list = g_slist_append (main_context_list, context);
567
568 #ifdef G_MAIN_POLL_DEBUG
569   if (_g_main_poll_debug)
570     g_print ("created context=%p\n", context);
571 #endif
572
573   G_UNLOCK (main_context_list);
574
575   return context;
576 }
577
578 /**
579  * g_main_context_default:
580  * 
581  * Returns the global default main context. This is the main context
582  * used for main loop functions when a main loop is not explicitly
583  * specified, and corresponds to the "main" main loop. See also
584  * g_main_context_get_thread_default().
585  * 
586  * Return value: (transfer none): the global default main context.
587  **/
588 GMainContext *
589 g_main_context_default (void)
590 {
591   /* Slow, but safe */
592   
593   G_LOCK (main_loop);
594
595   if (!default_main_context)
596     {
597       default_main_context = g_main_context_new ();
598 #ifdef G_MAIN_POLL_DEBUG
599       if (_g_main_poll_debug)
600         g_print ("default context=%p\n", default_main_context);
601 #endif
602     }
603
604   G_UNLOCK (main_loop);
605
606   return default_main_context;
607 }
608
609 static void
610 free_context_stack (gpointer data)
611 {
612   GQueue *stack = data;
613   GMainContext *context;
614
615   while (!g_queue_is_empty (stack))
616     {
617       context = g_queue_pop_head (stack);
618       g_main_context_release (context);
619       if (context)
620         g_main_context_unref (context);
621     }
622   g_queue_free (stack);
623 }
624
625 static GPrivate thread_context_stack = G_PRIVATE_INIT (free_context_stack);
626
627 /**
628  * g_main_context_push_thread_default:
629  * @context: a #GMainContext, or %NULL for the global default context
630  *
631  * Acquires @context and sets it as the thread-default context for the
632  * current thread. This will cause certain asynchronous operations
633  * (such as most <link linkend="gio">gio</link>-based I/O) which are
634  * started in this thread to run under @context and deliver their
635  * results to its main loop, rather than running under the global
636  * default context in the main thread. Note that calling this function
637  * changes the context returned by
638  * g_main_context_get_thread_default(), <emphasis>not</emphasis> the
639  * one returned by g_main_context_default(), so it does not affect the
640  * context used by functions like g_idle_add().
641  *
642  * Normally you would call this function shortly after creating a new
643  * thread, passing it a #GMainContext which will be run by a
644  * #GMainLoop in that thread, to set a new default context for all
645  * async operations in that thread. (In this case, you don't need to
646  * ever call g_main_context_pop_thread_default().) In some cases
647  * however, you may want to schedule a single operation in a
648  * non-default context, or temporarily use a non-default context in
649  * the main thread. In that case, you can wrap the call to the
650  * asynchronous operation inside a
651  * g_main_context_push_thread_default() /
652  * g_main_context_pop_thread_default() pair, but it is up to you to
653  * ensure that no other asynchronous operations accidentally get
654  * started while the non-default context is active.
655  *
656  * Beware that libraries that predate this function may not correctly
657  * handle being used from a thread with a thread-default context. Eg,
658  * see g_file_supports_thread_contexts().
659  *
660  * Since: 2.22
661  **/
662 void
663 g_main_context_push_thread_default (GMainContext *context)
664 {
665   GQueue *stack;
666   gboolean acquired_context;
667
668   acquired_context = g_main_context_acquire (context);
669   g_return_if_fail (acquired_context);
670
671   if (context == g_main_context_default ())
672     context = NULL;
673   else if (context)
674     g_main_context_ref (context);
675
676   stack = g_private_get (&thread_context_stack);
677   if (!stack)
678     {
679       stack = g_queue_new ();
680       g_private_set (&thread_context_stack, stack);
681     }
682
683   g_queue_push_head (stack, context);
684 }
685
686 /**
687  * g_main_context_pop_thread_default:
688  * @context: a #GMainContext object, or %NULL
689  *
690  * Pops @context off the thread-default context stack (verifying that
691  * it was on the top of the stack).
692  *
693  * Since: 2.22
694  **/
695 void
696 g_main_context_pop_thread_default (GMainContext *context)
697 {
698   GQueue *stack;
699
700   if (context == g_main_context_default ())
701     context = NULL;
702
703   stack = g_private_get (&thread_context_stack);
704
705   g_return_if_fail (stack != NULL);
706   g_return_if_fail (g_queue_peek_head (stack) == context);
707
708   g_queue_pop_head (stack);
709
710   g_main_context_release (context);
711   if (context)
712     g_main_context_unref (context);
713 }
714
715 /**
716  * g_main_context_get_thread_default:
717  *
718  * Gets the thread-default #GMainContext for this thread. Asynchronous
719  * operations that want to be able to be run in contexts other than
720  * the default one should call this method or
721  * g_main_context_ref_thread_default() to get a #GMainContext to add
722  * their #GSource<!-- -->s to. (Note that even in single-threaded
723  * programs applications may sometimes want to temporarily push a
724  * non-default context, so it is not safe to assume that this will
725  * always return %NULL if you are running in the default thread.)
726  *
727  * If you need to hold a reference on the context, use
728  * g_main_context_ref_thread_default() instead.
729  *
730  * Returns: (transfer none): the thread-default #GMainContext, or
731  * %NULL if the thread-default context is the global default context.
732  *
733  * Since: 2.22
734  **/
735 GMainContext *
736 g_main_context_get_thread_default (void)
737 {
738   GQueue *stack;
739
740   stack = g_private_get (&thread_context_stack);
741   if (stack)
742     return g_queue_peek_head (stack);
743   else
744     return NULL;
745 }
746
747 /**
748  * g_main_context_ref_thread_default:
749  *
750  * Gets the thread-default #GMainContext for this thread, as with
751  * g_main_context_get_thread_default(), but also adds a reference to
752  * it with g_main_context_ref(). In addition, unlike
753  * g_main_context_get_thread_default(), if the thread-default context
754  * is the global default context, this will return that #GMainContext
755  * (with a ref added to it) rather than returning %NULL.
756  *
757  * Returns: (transfer full): the thread-default #GMainContext. Unref
758  *     with g_main_context_unref() when you are done with it.
759  *
760  * Since: 2.32
761  */
762 GMainContext *
763 g_main_context_ref_thread_default (void)
764 {
765   GMainContext *context;
766
767   context = g_main_context_get_thread_default ();
768   if (!context)
769     context = g_main_context_default ();
770   return g_main_context_ref (context);
771 }
772
773 /* Hooks for adding to the main loop */
774
775 /**
776  * g_source_new:
777  * @source_funcs: structure containing functions that implement
778  *                the sources behavior.
779  * @struct_size: size of the #GSource structure to create.
780  * 
781  * Creates a new #GSource structure. The size is specified to
782  * allow creating structures derived from #GSource that contain
783  * additional data. The size passed in must be at least
784  * <literal>sizeof (GSource)</literal>.
785  * 
786  * The source will not initially be associated with any #GMainContext
787  * and must be added to one with g_source_attach() before it will be
788  * executed.
789  * 
790  * Return value: the newly-created #GSource.
791  **/
792 GSource *
793 g_source_new (GSourceFuncs *source_funcs,
794               guint         struct_size)
795 {
796   GSource *source;
797
798   g_return_val_if_fail (source_funcs != NULL, NULL);
799   g_return_val_if_fail (struct_size >= sizeof (GSource), NULL);
800   
801   source = (GSource*) g_malloc0 (struct_size);
802
803   source->source_funcs = source_funcs;
804   source->ref_count = 1;
805   
806   source->priority = G_PRIORITY_DEFAULT;
807
808   source->flags = G_HOOK_FLAG_ACTIVE;
809
810   /* NULL/0 initialization for all other fields */
811   
812   return source;
813 }
814
815 /* Holds context's lock
816  */
817 static void
818 g_source_list_add (GSource      *source,
819                    GMainContext *context)
820 {
821   GSource *tmp_source, *last_source;
822   
823   if (source->priv && source->priv->parent_source)
824     {
825       /* Put the source immediately before its parent */
826       tmp_source = source->priv->parent_source;
827       last_source = source->priv->parent_source->prev;
828     }
829   else
830     {
831       last_source = NULL;
832       tmp_source = context->source_list;
833       while (tmp_source && tmp_source->priority <= source->priority)
834         {
835           last_source = tmp_source;
836           tmp_source = tmp_source->next;
837         }
838     }
839
840   source->next = tmp_source;
841   if (tmp_source)
842     tmp_source->prev = source;
843   
844   source->prev = last_source;
845   if (last_source)
846     last_source->next = source;
847   else
848     context->source_list = source;
849 }
850
851 /* Holds context's lock
852  */
853 static void
854 g_source_list_remove (GSource      *source,
855                       GMainContext *context)
856 {
857   if (source->prev)
858     source->prev->next = source->next;
859   else
860     context->source_list = source->next;
861
862   if (source->next)
863     source->next->prev = source->prev;
864
865   source->prev = NULL;
866   source->next = NULL;
867 }
868
869 static guint
870 g_source_attach_unlocked (GSource      *source,
871                           GMainContext *context)
872 {
873   guint result = 0;
874   GSList *tmp_list;
875
876   source->context = context;
877   result = source->source_id = context->next_id++;
878
879   source->ref_count++;
880   g_source_list_add (source, context);
881
882   tmp_list = source->poll_fds;
883   while (tmp_list)
884     {
885       g_main_context_add_poll_unlocked (context, source->priority, tmp_list->data);
886       tmp_list = tmp_list->next;
887     }
888
889   if (source->priv)
890     {
891       tmp_list = source->priv->child_sources;
892       while (tmp_list)
893         {
894           g_source_attach_unlocked (tmp_list->data, context);
895           tmp_list = tmp_list->next;
896         }
897     }
898
899   return result;
900 }
901
902 /**
903  * g_source_attach:
904  * @source: a #GSource
905  * @context: a #GMainContext (if %NULL, the default context will be used)
906  * 
907  * Adds a #GSource to a @context so that it will be executed within
908  * that context. Remove it by calling g_source_destroy().
909  *
910  * Return value: the ID (greater than 0) for the source within the 
911  *   #GMainContext. 
912  **/
913 guint
914 g_source_attach (GSource      *source,
915                  GMainContext *context)
916 {
917   guint result = 0;
918
919   g_return_val_if_fail (source->context == NULL, 0);
920   g_return_val_if_fail (!SOURCE_DESTROYED (source), 0);
921   
922   if (!context)
923     context = g_main_context_default ();
924
925   LOCK_CONTEXT (context);
926
927   result = g_source_attach_unlocked (source, context);
928
929   /* If another thread has acquired the context, wake it up since it
930    * might be in poll() right now.
931    */
932   if (context->owner && context->owner != G_THREAD_SELF)
933     g_wakeup_signal (context->wakeup);
934
935   UNLOCK_CONTEXT (context);
936
937   return result;
938 }
939
940 static void
941 g_source_destroy_internal (GSource      *source,
942                            GMainContext *context,
943                            gboolean      have_lock)
944 {
945   if (!have_lock)
946     LOCK_CONTEXT (context);
947   
948   if (!SOURCE_DESTROYED (source))
949     {
950       GSList *tmp_list;
951       gpointer old_cb_data;
952       GSourceCallbackFuncs *old_cb_funcs;
953       
954       source->flags &= ~G_HOOK_FLAG_ACTIVE;
955
956       old_cb_data = source->callback_data;
957       old_cb_funcs = source->callback_funcs;
958
959       source->callback_data = NULL;
960       source->callback_funcs = NULL;
961
962       if (old_cb_funcs)
963         {
964           UNLOCK_CONTEXT (context);
965           old_cb_funcs->unref (old_cb_data);
966           LOCK_CONTEXT (context);
967         }
968
969       if (!SOURCE_BLOCKED (source))
970         {
971           tmp_list = source->poll_fds;
972           while (tmp_list)
973             {
974               g_main_context_remove_poll_unlocked (context, tmp_list->data);
975               tmp_list = tmp_list->next;
976             }
977         }
978
979       if (source->priv && source->priv->child_sources)
980         {
981           /* This is safe because even if a child_source finalizer or
982            * closure notify tried to modify source->priv->child_sources
983            * from outside the lock, it would fail since
984            * SOURCE_DESTROYED(source) is now TRUE.
985            */
986           tmp_list = source->priv->child_sources;
987           while (tmp_list)
988             {
989               g_source_destroy_internal (tmp_list->data, context, TRUE);
990               g_source_unref_internal (tmp_list->data, context, TRUE);
991               tmp_list = tmp_list->next;
992             }
993           g_slist_free (source->priv->child_sources);
994           source->priv->child_sources = NULL;
995         }
996           
997       g_source_unref_internal (source, context, TRUE);
998     }
999
1000   if (!have_lock)
1001     UNLOCK_CONTEXT (context);
1002 }
1003
1004 /**
1005  * g_source_destroy:
1006  * @source: a #GSource
1007  * 
1008  * Removes a source from its #GMainContext, if any, and mark it as
1009  * destroyed.  The source cannot be subsequently added to another
1010  * context.
1011  **/
1012 void
1013 g_source_destroy (GSource *source)
1014 {
1015   GMainContext *context;
1016   
1017   g_return_if_fail (source != NULL);
1018   
1019   context = source->context;
1020   
1021   if (context)
1022     g_source_destroy_internal (source, context, FALSE);
1023   else
1024     source->flags &= ~G_HOOK_FLAG_ACTIVE;
1025 }
1026
1027 /**
1028  * g_source_get_id:
1029  * @source: a #GSource
1030  * 
1031  * Returns the numeric ID for a particular source. The ID of a source
1032  * is a positive integer which is unique within a particular main loop 
1033  * context. The reverse
1034  * mapping from ID to source is done by g_main_context_find_source_by_id().
1035  *
1036  * Return value: the ID (greater than 0) for the source
1037  **/
1038 guint
1039 g_source_get_id (GSource *source)
1040 {
1041   guint result;
1042   
1043   g_return_val_if_fail (source != NULL, 0);
1044   g_return_val_if_fail (source->context != NULL, 0);
1045
1046   LOCK_CONTEXT (source->context);
1047   result = source->source_id;
1048   UNLOCK_CONTEXT (source->context);
1049   
1050   return result;
1051 }
1052
1053 /**
1054  * g_source_get_context:
1055  * @source: a #GSource
1056  * 
1057  * Gets the #GMainContext with which the source is associated.
1058  * Calling this function on a destroyed source is an error.
1059  * 
1060  * Return value: (transfer none): the #GMainContext with which the
1061  *               source is associated, or %NULL if the context has not
1062  *               yet been added to a source.
1063  **/
1064 GMainContext *
1065 g_source_get_context (GSource *source)
1066 {
1067   g_return_val_if_fail (!SOURCE_DESTROYED (source), NULL);
1068
1069   return source->context;
1070 }
1071
1072 /**
1073  * g_source_add_poll:
1074  * @source:a #GSource 
1075  * @fd: a #GPollFD structure holding information about a file
1076  *      descriptor to watch.
1077  * 
1078  * Adds a file descriptor to the set of file descriptors polled for
1079  * this source. This is usually combined with g_source_new() to add an
1080  * event source. The event source's check function will typically test
1081  * the @revents field in the #GPollFD struct and return %TRUE if events need
1082  * to be processed.
1083  **/
1084 void
1085 g_source_add_poll (GSource *source,
1086                    GPollFD *fd)
1087 {
1088   GMainContext *context;
1089   
1090   g_return_if_fail (source != NULL);
1091   g_return_if_fail (fd != NULL);
1092   g_return_if_fail (!SOURCE_DESTROYED (source));
1093   
1094   context = source->context;
1095
1096   if (context)
1097     LOCK_CONTEXT (context);
1098   
1099   source->poll_fds = g_slist_prepend (source->poll_fds, fd);
1100
1101   if (context)
1102     {
1103       if (!SOURCE_BLOCKED (source))
1104         g_main_context_add_poll_unlocked (context, source->priority, fd);
1105       UNLOCK_CONTEXT (context);
1106     }
1107 }
1108
1109 /**
1110  * g_source_remove_poll:
1111  * @source:a #GSource 
1112  * @fd: a #GPollFD structure previously passed to g_source_add_poll().
1113  * 
1114  * Removes a file descriptor from the set of file descriptors polled for
1115  * this source. 
1116  **/
1117 void
1118 g_source_remove_poll (GSource *source,
1119                       GPollFD *fd)
1120 {
1121   GMainContext *context;
1122   
1123   g_return_if_fail (source != NULL);
1124   g_return_if_fail (fd != NULL);
1125   g_return_if_fail (!SOURCE_DESTROYED (source));
1126   
1127   context = source->context;
1128
1129   if (context)
1130     LOCK_CONTEXT (context);
1131   
1132   source->poll_fds = g_slist_remove (source->poll_fds, fd);
1133
1134   if (context)
1135     {
1136       if (!SOURCE_BLOCKED (source))
1137         g_main_context_remove_poll_unlocked (context, fd);
1138       UNLOCK_CONTEXT (context);
1139     }
1140 }
1141
1142 /**
1143  * g_source_add_child_source:
1144  * @source:a #GSource
1145  * @child_source: a second #GSource that @source should "poll"
1146  *
1147  * Adds @child_source to @source as a "polled" source; when @source is
1148  * added to a #GMainContext, @child_source will be automatically added
1149  * with the same priority, when @child_source is triggered, it will
1150  * cause @source to dispatch (in addition to calling its own
1151  * callback), and when @source is destroyed, it will destroy
1152  * @child_source as well. (@source will also still be dispatched if
1153  * its own prepare/check functions indicate that it is ready.)
1154  *
1155  * If you don't need @child_source to do anything on its own when it
1156  * triggers, you can call g_source_set_dummy_callback() on it to set a
1157  * callback that does nothing (except return %TRUE if appropriate).
1158  *
1159  * @source will hold a reference on @child_source while @child_source
1160  * is attached to it.
1161  *
1162  * Since: 2.28
1163  **/
1164 void
1165 g_source_add_child_source (GSource *source,
1166                            GSource *child_source)
1167 {
1168   GMainContext *context;
1169
1170   g_return_if_fail (source != NULL);
1171   g_return_if_fail (child_source != NULL);
1172   g_return_if_fail (!SOURCE_DESTROYED (source));
1173   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1174   g_return_if_fail (child_source->context == NULL);
1175   g_return_if_fail (child_source->priv == NULL || child_source->priv->parent_source == NULL);
1176
1177   context = source->context;
1178
1179   if (context)
1180     LOCK_CONTEXT (context);
1181
1182   if (!source->priv)
1183     source->priv = g_slice_new0 (GSourcePrivate);
1184   if (!child_source->priv)
1185     child_source->priv = g_slice_new0 (GSourcePrivate);
1186
1187   source->priv->child_sources = g_slist_prepend (source->priv->child_sources,
1188                                                  g_source_ref (child_source));
1189   child_source->priv->parent_source = source;
1190   g_source_set_priority_unlocked (child_source, context, source->priority);
1191
1192   if (context)
1193     {
1194       UNLOCK_CONTEXT (context);
1195       g_source_attach (child_source, context);
1196     }
1197 }
1198
1199 /**
1200  * g_source_remove_child_source:
1201  * @source:a #GSource
1202  * @child_source: a #GSource previously passed to
1203  *     g_source_add_child_source().
1204  *
1205  * Detaches @child_source from @source and destroys it.
1206  *
1207  * Since: 2.28
1208  **/
1209 void
1210 g_source_remove_child_source (GSource *source,
1211                               GSource *child_source)
1212 {
1213   GMainContext *context;
1214
1215   g_return_if_fail (source != NULL);
1216   g_return_if_fail (child_source != NULL);
1217   g_return_if_fail (child_source->priv != NULL && child_source->priv->parent_source == source);
1218   g_return_if_fail (!SOURCE_DESTROYED (source));
1219   g_return_if_fail (!SOURCE_DESTROYED (child_source));
1220
1221   context = source->context;
1222
1223   if (context)
1224     LOCK_CONTEXT (context);
1225
1226   source->priv->child_sources = g_slist_remove (source->priv->child_sources, child_source);
1227   g_source_destroy_internal (child_source, context, TRUE);
1228   g_source_unref_internal (child_source, context, TRUE);
1229
1230   if (context)
1231     UNLOCK_CONTEXT (context);
1232 }
1233
1234 /**
1235  * g_source_set_callback_indirect:
1236  * @source: the source
1237  * @callback_data: pointer to callback data "object"
1238  * @callback_funcs: functions for reference counting @callback_data
1239  *                  and getting the callback and data
1240  * 
1241  * Sets the callback function storing the data as a refcounted callback
1242  * "object". This is used internally. Note that calling 
1243  * g_source_set_callback_indirect() assumes
1244  * an initial reference count on @callback_data, and thus
1245  * @callback_funcs->unref will eventually be called once more
1246  * than @callback_funcs->ref.
1247  **/
1248 void
1249 g_source_set_callback_indirect (GSource              *source,
1250                                 gpointer              callback_data,
1251                                 GSourceCallbackFuncs *callback_funcs)
1252 {
1253   GMainContext *context;
1254   gpointer old_cb_data;
1255   GSourceCallbackFuncs *old_cb_funcs;
1256   
1257   g_return_if_fail (source != NULL);
1258   g_return_if_fail (callback_funcs != NULL || callback_data == NULL);
1259
1260   context = source->context;
1261
1262   if (context)
1263     LOCK_CONTEXT (context);
1264
1265   old_cb_data = source->callback_data;
1266   old_cb_funcs = source->callback_funcs;
1267
1268   source->callback_data = callback_data;
1269   source->callback_funcs = callback_funcs;
1270   
1271   if (context)
1272     UNLOCK_CONTEXT (context);
1273   
1274   if (old_cb_funcs)
1275     old_cb_funcs->unref (old_cb_data);
1276 }
1277
1278 static void
1279 g_source_callback_ref (gpointer cb_data)
1280 {
1281   GSourceCallback *callback = cb_data;
1282
1283   callback->ref_count++;
1284 }
1285
1286
1287 static void
1288 g_source_callback_unref (gpointer cb_data)
1289 {
1290   GSourceCallback *callback = cb_data;
1291
1292   callback->ref_count--;
1293   if (callback->ref_count == 0)
1294     {
1295       if (callback->notify)
1296         callback->notify (callback->data);
1297       g_free (callback);
1298     }
1299 }
1300
1301 static void
1302 g_source_callback_get (gpointer     cb_data,
1303                        GSource     *source, 
1304                        GSourceFunc *func,
1305                        gpointer    *data)
1306 {
1307   GSourceCallback *callback = cb_data;
1308
1309   *func = callback->func;
1310   *data = callback->data;
1311 }
1312
1313 static GSourceCallbackFuncs g_source_callback_funcs = {
1314   g_source_callback_ref,
1315   g_source_callback_unref,
1316   g_source_callback_get,
1317 };
1318
1319 /**
1320  * g_source_set_callback:
1321  * @source: the source
1322  * @func: a callback function
1323  * @data: the data to pass to callback function
1324  * @notify: a function to call when @data is no longer in use, or %NULL.
1325  * 
1326  * Sets the callback function for a source. The callback for a source is
1327  * called from the source's dispatch function.
1328  *
1329  * The exact type of @func depends on the type of source; ie. you
1330  * should not count on @func being called with @data as its first
1331  * parameter.
1332  * 
1333  * Typically, you won't use this function. Instead use functions specific
1334  * to the type of source you are using.
1335  **/
1336 void
1337 g_source_set_callback (GSource        *source,
1338                        GSourceFunc     func,
1339                        gpointer        data,
1340                        GDestroyNotify  notify)
1341 {
1342   GSourceCallback *new_callback;
1343
1344   g_return_if_fail (source != NULL);
1345
1346   new_callback = g_new (GSourceCallback, 1);
1347
1348   new_callback->ref_count = 1;
1349   new_callback->func = func;
1350   new_callback->data = data;
1351   new_callback->notify = notify;
1352
1353   g_source_set_callback_indirect (source, new_callback, &g_source_callback_funcs);
1354 }
1355
1356
1357 /**
1358  * g_source_set_funcs:
1359  * @source: a #GSource
1360  * @funcs: the new #GSourceFuncs
1361  * 
1362  * Sets the source functions (can be used to override 
1363  * default implementations) of an unattached source.
1364  * 
1365  * Since: 2.12
1366  */
1367 void
1368 g_source_set_funcs (GSource     *source,
1369                    GSourceFuncs *funcs)
1370 {
1371   g_return_if_fail (source != NULL);
1372   g_return_if_fail (source->context == NULL);
1373   g_return_if_fail (source->ref_count > 0);
1374   g_return_if_fail (funcs != NULL);
1375
1376   source->source_funcs = funcs;
1377 }
1378
1379 static void
1380 g_source_set_priority_unlocked (GSource      *source,
1381                                 GMainContext *context,
1382                                 gint          priority)
1383 {
1384   GSList *tmp_list;
1385   
1386   source->priority = priority;
1387
1388   if (context)
1389     {
1390       /* Remove the source from the context's source and then
1391        * add it back so it is sorted in the correct place
1392        */
1393       g_source_list_remove (source, source->context);
1394       g_source_list_add (source, source->context);
1395
1396       if (!SOURCE_BLOCKED (source))
1397         {
1398           tmp_list = source->poll_fds;
1399           while (tmp_list)
1400             {
1401               g_main_context_remove_poll_unlocked (context, tmp_list->data);
1402               g_main_context_add_poll_unlocked (context, priority, tmp_list->data);
1403               
1404               tmp_list = tmp_list->next;
1405             }
1406         }
1407     }
1408
1409   if (source->priv && source->priv->child_sources)
1410     {
1411       tmp_list = source->priv->child_sources;
1412       while (tmp_list)
1413         {
1414           g_source_set_priority_unlocked (tmp_list->data, context, priority);
1415           tmp_list = tmp_list->next;
1416         }
1417     }
1418 }
1419
1420 /**
1421  * g_source_set_priority:
1422  * @source: a #GSource
1423  * @priority: the new priority.
1424  *
1425  * Sets the priority of a source. While the main loop is being run, a
1426  * source will be dispatched if it is ready to be dispatched and no
1427  * sources at a higher (numerically smaller) priority are ready to be
1428  * dispatched.
1429  **/
1430 void
1431 g_source_set_priority (GSource  *source,
1432                        gint      priority)
1433 {
1434   GMainContext *context;
1435
1436   g_return_if_fail (source != NULL);
1437
1438   context = source->context;
1439
1440   if (context)
1441     LOCK_CONTEXT (context);
1442   g_source_set_priority_unlocked (source, context, priority);
1443   if (context)
1444     UNLOCK_CONTEXT (source->context);
1445 }
1446
1447 /**
1448  * g_source_get_priority:
1449  * @source: a #GSource
1450  * 
1451  * Gets the priority of a source.
1452  * 
1453  * Return value: the priority of the source
1454  **/
1455 gint
1456 g_source_get_priority (GSource *source)
1457 {
1458   g_return_val_if_fail (source != NULL, 0);
1459
1460   return source->priority;
1461 }
1462
1463 /**
1464  * g_source_set_can_recurse:
1465  * @source: a #GSource
1466  * @can_recurse: whether recursion is allowed for this source
1467  * 
1468  * Sets whether a source can be called recursively. If @can_recurse is
1469  * %TRUE, then while the source is being dispatched then this source
1470  * will be processed normally. Otherwise, all processing of this
1471  * source is blocked until the dispatch function returns.
1472  **/
1473 void
1474 g_source_set_can_recurse (GSource  *source,
1475                           gboolean  can_recurse)
1476 {
1477   GMainContext *context;
1478   
1479   g_return_if_fail (source != NULL);
1480
1481   context = source->context;
1482
1483   if (context)
1484     LOCK_CONTEXT (context);
1485   
1486   if (can_recurse)
1487     source->flags |= G_SOURCE_CAN_RECURSE;
1488   else
1489     source->flags &= ~G_SOURCE_CAN_RECURSE;
1490
1491   if (context)
1492     UNLOCK_CONTEXT (context);
1493 }
1494
1495 /**
1496  * g_source_get_can_recurse:
1497  * @source: a #GSource
1498  * 
1499  * Checks whether a source is allowed to be called recursively.
1500  * see g_source_set_can_recurse().
1501  * 
1502  * Return value: whether recursion is allowed.
1503  **/
1504 gboolean
1505 g_source_get_can_recurse (GSource  *source)
1506 {
1507   g_return_val_if_fail (source != NULL, FALSE);
1508   
1509   return (source->flags & G_SOURCE_CAN_RECURSE) != 0;
1510 }
1511
1512
1513 /**
1514  * g_source_set_name:
1515  * @source: a #GSource
1516  * @name: debug name for the source
1517  *
1518  * Sets a name for the source, used in debugging and profiling.
1519  * The name defaults to #NULL.
1520  *
1521  * The source name should describe in a human-readable way
1522  * what the source does. For example, "X11 event queue"
1523  * or "GTK+ repaint idle handler" or whatever it is.
1524  *
1525  * It is permitted to call this function multiple times, but is not
1526  * recommended due to the potential performance impact.  For example,
1527  * one could change the name in the "check" function of a #GSourceFuncs 
1528  * to include details like the event type in the source name.
1529  *
1530  * Since: 2.26
1531  **/
1532 void
1533 g_source_set_name (GSource    *source,
1534                    const char *name)
1535 {
1536   g_return_if_fail (source != NULL);
1537
1538   /* setting back to NULL is allowed, just because it's
1539    * weird if get_name can return NULL but you can't
1540    * set that.
1541    */
1542
1543   g_free (source->name);
1544   source->name = g_strdup (name);
1545 }
1546
1547 /**
1548  * g_source_get_name:
1549  * @source: a #GSource
1550  *
1551  * Gets a name for the source, used in debugging and profiling.
1552  * The name may be #NULL if it has never been set with
1553  * g_source_set_name().
1554  *
1555  * Return value: the name of the source
1556  * Since: 2.26
1557  **/
1558 const char *
1559 g_source_get_name (GSource *source)
1560 {
1561   g_return_val_if_fail (source != NULL, NULL);
1562
1563   return source->name;
1564 }
1565
1566 /**
1567  * g_source_set_name_by_id:
1568  * @tag: a #GSource ID
1569  * @name: debug name for the source
1570  *
1571  * Sets the name of a source using its ID.
1572  *
1573  * This is a convenience utility to set source names from the return
1574  * value of g_idle_add(), g_timeout_add(), etc.
1575  *
1576  * Since: 2.26
1577  **/
1578 void
1579 g_source_set_name_by_id (guint           tag,
1580                          const char     *name)
1581 {
1582   GSource *source;
1583
1584   g_return_if_fail (tag > 0);
1585
1586   source = g_main_context_find_source_by_id (NULL, tag);
1587   if (source == NULL)
1588     return;
1589
1590   g_source_set_name (source, name);
1591 }
1592
1593
1594 /**
1595  * g_source_ref:
1596  * @source: a #GSource
1597  * 
1598  * Increases the reference count on a source by one.
1599  * 
1600  * Return value: @source
1601  **/
1602 GSource *
1603 g_source_ref (GSource *source)
1604 {
1605   GMainContext *context;
1606   
1607   g_return_val_if_fail (source != NULL, NULL);
1608
1609   context = source->context;
1610
1611   if (context)
1612     LOCK_CONTEXT (context);
1613
1614   source->ref_count++;
1615
1616   if (context)
1617     UNLOCK_CONTEXT (context);
1618
1619   return source;
1620 }
1621
1622 /* g_source_unref() but possible to call within context lock
1623  */
1624 static void
1625 g_source_unref_internal (GSource      *source,
1626                          GMainContext *context,
1627                          gboolean      have_lock)
1628 {
1629   gpointer old_cb_data = NULL;
1630   GSourceCallbackFuncs *old_cb_funcs = NULL;
1631
1632   g_return_if_fail (source != NULL);
1633   
1634   if (!have_lock && context)
1635     LOCK_CONTEXT (context);
1636
1637   source->ref_count--;
1638   if (source->ref_count == 0)
1639     {
1640       old_cb_data = source->callback_data;
1641       old_cb_funcs = source->callback_funcs;
1642
1643       source->callback_data = NULL;
1644       source->callback_funcs = NULL;
1645
1646       if (context)
1647         {
1648           if (!SOURCE_DESTROYED (source))
1649             g_warning (G_STRLOC ": ref_count == 0, but source was still attached to a context!");
1650           g_source_list_remove (source, context);
1651         }
1652
1653       if (source->source_funcs->finalize)
1654         {
1655           if (context)
1656             UNLOCK_CONTEXT (context);
1657           source->source_funcs->finalize (source);
1658           if (context)
1659             LOCK_CONTEXT (context);
1660         }
1661
1662       g_free (source->name);
1663       source->name = NULL;
1664
1665       g_slist_free (source->poll_fds);
1666       source->poll_fds = NULL;
1667
1668       if (source->priv)
1669         {
1670           g_slice_free (GSourcePrivate, source->priv);
1671           source->priv = NULL;
1672         }
1673
1674       g_free (source);
1675     }
1676   
1677   if (!have_lock && context)
1678     UNLOCK_CONTEXT (context);
1679
1680   if (old_cb_funcs)
1681     {
1682       if (have_lock)
1683         UNLOCK_CONTEXT (context);
1684       
1685       old_cb_funcs->unref (old_cb_data);
1686
1687       if (have_lock)
1688         LOCK_CONTEXT (context);
1689     }
1690 }
1691
1692 /**
1693  * g_source_unref:
1694  * @source: a #GSource
1695  * 
1696  * Decreases the reference count of a source by one. If the
1697  * resulting reference count is zero the source and associated
1698  * memory will be destroyed. 
1699  **/
1700 void
1701 g_source_unref (GSource *source)
1702 {
1703   g_return_if_fail (source != NULL);
1704
1705   g_source_unref_internal (source, source->context, FALSE);
1706 }
1707
1708 /**
1709  * g_main_context_find_source_by_id:
1710  * @context: a #GMainContext (if %NULL, the default context will be used)
1711  * @source_id: the source ID, as returned by g_source_get_id(). 
1712  * 
1713  * Finds a #GSource given a pair of context and ID.
1714  * 
1715  * Return value: (transfer none): the #GSource if found, otherwise, %NULL
1716  **/
1717 GSource *
1718 g_main_context_find_source_by_id (GMainContext *context,
1719                                   guint         source_id)
1720 {
1721   GSource *source;
1722   
1723   g_return_val_if_fail (source_id > 0, NULL);
1724
1725   if (context == NULL)
1726     context = g_main_context_default ();
1727   
1728   LOCK_CONTEXT (context);
1729   
1730   source = context->source_list;
1731   while (source)
1732     {
1733       if (!SOURCE_DESTROYED (source) &&
1734           source->source_id == source_id)
1735         break;
1736       source = source->next;
1737     }
1738
1739   UNLOCK_CONTEXT (context);
1740
1741   return source;
1742 }
1743
1744 /**
1745  * g_main_context_find_source_by_funcs_user_data:
1746  * @context: a #GMainContext (if %NULL, the default context will be used).
1747  * @funcs: the @source_funcs passed to g_source_new().
1748  * @user_data: the user data from the callback.
1749  * 
1750  * Finds a source with the given source functions and user data.  If
1751  * multiple sources exist with the same source function and user data,
1752  * the first one found will be returned.
1753  * 
1754  * Return value: (transfer none): the source, if one was found, otherwise %NULL
1755  **/
1756 GSource *
1757 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1758                                                GSourceFuncs *funcs,
1759                                                gpointer      user_data)
1760 {
1761   GSource *source;
1762   
1763   g_return_val_if_fail (funcs != NULL, NULL);
1764
1765   if (context == NULL)
1766     context = g_main_context_default ();
1767   
1768   LOCK_CONTEXT (context);
1769
1770   source = context->source_list;
1771   while (source)
1772     {
1773       if (!SOURCE_DESTROYED (source) &&
1774           source->source_funcs == funcs &&
1775           source->callback_funcs)
1776         {
1777           GSourceFunc callback;
1778           gpointer callback_data;
1779
1780           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1781           
1782           if (callback_data == user_data)
1783             break;
1784         }
1785       source = source->next;
1786     }
1787
1788   UNLOCK_CONTEXT (context);
1789
1790   return source;
1791 }
1792
1793 /**
1794  * g_main_context_find_source_by_user_data:
1795  * @context: a #GMainContext
1796  * @user_data: the user_data for the callback.
1797  * 
1798  * Finds a source with the given user data for the callback.  If
1799  * multiple sources exist with the same user data, the first
1800  * one found will be returned.
1801  * 
1802  * Return value: (transfer none): the source, if one was found, otherwise %NULL
1803  **/
1804 GSource *
1805 g_main_context_find_source_by_user_data (GMainContext *context,
1806                                          gpointer      user_data)
1807 {
1808   GSource *source;
1809   
1810   if (context == NULL)
1811     context = g_main_context_default ();
1812   
1813   LOCK_CONTEXT (context);
1814
1815   source = context->source_list;
1816   while (source)
1817     {
1818       if (!SOURCE_DESTROYED (source) &&
1819           source->callback_funcs)
1820         {
1821           GSourceFunc callback;
1822           gpointer callback_data = NULL;
1823
1824           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1825
1826           if (callback_data == user_data)
1827             break;
1828         }
1829       source = source->next;
1830     }
1831
1832   UNLOCK_CONTEXT (context);
1833
1834   return source;
1835 }
1836
1837 /**
1838  * g_source_remove:
1839  * @tag: the ID of the source to remove.
1840  * 
1841  * Removes the source with the given id from the default main context. 
1842  * The id of
1843  * a #GSource is given by g_source_get_id(), or will be returned by the
1844  * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1845  * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1846  * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1847  *
1848  * See also g_source_destroy(). You must use g_source_destroy() for sources
1849  * added to a non-default main context.
1850  *
1851  * Return value: %TRUE if the source was found and removed.
1852  **/
1853 gboolean
1854 g_source_remove (guint tag)
1855 {
1856   GSource *source;
1857   
1858   g_return_val_if_fail (tag > 0, FALSE);
1859
1860   source = g_main_context_find_source_by_id (NULL, tag);
1861   if (source)
1862     g_source_destroy (source);
1863
1864   return source != NULL;
1865 }
1866
1867 /**
1868  * g_source_remove_by_user_data:
1869  * @user_data: the user_data for the callback.
1870  * 
1871  * Removes a source from the default main loop context given the user
1872  * data for the callback. If multiple sources exist with the same user
1873  * data, only one will be destroyed.
1874  * 
1875  * Return value: %TRUE if a source was found and removed. 
1876  **/
1877 gboolean
1878 g_source_remove_by_user_data (gpointer user_data)
1879 {
1880   GSource *source;
1881   
1882   source = g_main_context_find_source_by_user_data (NULL, user_data);
1883   if (source)
1884     {
1885       g_source_destroy (source);
1886       return TRUE;
1887     }
1888   else
1889     return FALSE;
1890 }
1891
1892 /**
1893  * g_source_remove_by_funcs_user_data:
1894  * @funcs: The @source_funcs passed to g_source_new()
1895  * @user_data: the user data for the callback
1896  * 
1897  * Removes a source from the default main loop context given the
1898  * source functions and user data. If multiple sources exist with the
1899  * same source functions and user data, only one will be destroyed.
1900  * 
1901  * Return value: %TRUE if a source was found and removed. 
1902  **/
1903 gboolean
1904 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1905                                     gpointer      user_data)
1906 {
1907   GSource *source;
1908
1909   g_return_val_if_fail (funcs != NULL, FALSE);
1910
1911   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1912   if (source)
1913     {
1914       g_source_destroy (source);
1915       return TRUE;
1916     }
1917   else
1918     return FALSE;
1919 }
1920
1921 /**
1922  * g_get_current_time:
1923  * @result: #GTimeVal structure in which to store current time.
1924  *
1925  * Equivalent to the UNIX gettimeofday() function, but portable.
1926  *
1927  * You may find g_get_real_time() to be more convenient.
1928  **/
1929 void
1930 g_get_current_time (GTimeVal *result)
1931 {
1932 #ifndef G_OS_WIN32
1933   struct timeval r;
1934
1935   g_return_if_fail (result != NULL);
1936
1937   /*this is required on alpha, there the timeval structs are int's
1938     not longs and a cast only would fail horribly*/
1939   gettimeofday (&r, NULL);
1940   result->tv_sec = r.tv_sec;
1941   result->tv_usec = r.tv_usec;
1942 #else
1943   FILETIME ft;
1944   guint64 time64;
1945
1946   g_return_if_fail (result != NULL);
1947
1948   GetSystemTimeAsFileTime (&ft);
1949   memmove (&time64, &ft, sizeof (FILETIME));
1950
1951   /* Convert from 100s of nanoseconds since 1601-01-01
1952    * to Unix epoch. Yes, this is Y2038 unsafe.
1953    */
1954   time64 -= G_GINT64_CONSTANT (116444736000000000);
1955   time64 /= 10;
1956
1957   result->tv_sec = time64 / 1000000;
1958   result->tv_usec = time64 % 1000000;
1959 #endif
1960 }
1961
1962 /**
1963  * g_get_real_time:
1964  *
1965  * Queries the system wall-clock time.
1966  *
1967  * This call is functionally equivalent to g_get_current_time() except
1968  * that the return value is often more convenient than dealing with a
1969  * #GTimeVal.
1970  *
1971  * You should only use this call if you are actually interested in the real
1972  * wall-clock time.  g_get_monotonic_time() is probably more useful for
1973  * measuring intervals.
1974  *
1975  * Returns: the number of microseconds since January 1, 1970 UTC.
1976  *
1977  * Since: 2.28
1978  **/
1979 gint64
1980 g_get_real_time (void)
1981 {
1982   GTimeVal tv;
1983
1984   g_get_current_time (&tv);
1985
1986   return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
1987 }
1988
1989 /**
1990  * g_get_monotonic_time:
1991  *
1992  * Queries the system monotonic time, if available.
1993  *
1994  * On POSIX systems with clock_gettime() and %CLOCK_MONOTONIC this call
1995  * is a very shallow wrapper for that.  Otherwise, we make a best effort
1996  * that probably involves returning the wall clock time (with at least
1997  * microsecond accuracy, subject to the limitations of the OS kernel).
1998  *
1999  * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2000  * time spent while the machine is suspended.
2001  *
2002  * On Windows, "limitations of the OS kernel" is a rather substantial
2003  * statement.  Depending on the configuration of the system, the wall
2004  * clock time is updated as infrequently as 64 times a second (which
2005  * is approximately every 16ms).
2006  *
2007  * Returns: the monotonic time, in microseconds
2008  *
2009  * Since: 2.28
2010  **/
2011 gint64
2012 g_get_monotonic_time (void)
2013 {
2014 #ifdef HAVE_CLOCK_GETTIME
2015   /* librt clock_gettime() is our first choice */
2016   {
2017 #ifdef HAVE_MONOTONIC_CLOCK
2018     static volatile gsize clockid = 0;
2019 #else
2020     static clockid_t clockid = CLOCK_REALTIME;
2021 #endif
2022     struct timespec ts;
2023
2024 #ifdef HAVE_MONOTONIC_CLOCK
2025     if (g_once_init_enter (&clockid))
2026       {
2027         clockid_t best_clockid;
2028
2029         if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2030           best_clockid = CLOCK_MONOTONIC;
2031         else
2032           best_clockid = CLOCK_REALTIME;
2033         g_once_init_leave (&clockid, (gsize)best_clockid);
2034       }
2035 #endif
2036
2037     clock_gettime (clockid, &ts);
2038
2039     /* In theory monotonic time can have any epoch.
2040      *
2041      * glib presently assumes the following:
2042      *
2043      *   1) The epoch comes some time after the birth of Jesus of Nazareth, but
2044      *      not more than 10000 years later.
2045      *
2046      *   2) The current time also falls sometime within this range.
2047      *
2048      * These two reasonable assumptions leave us with a maximum deviation from
2049      * the epoch of 10000 years, or 315569520000000000 seconds.
2050      *
2051      * If we restrict ourselves to this range then the number of microseconds
2052      * will always fit well inside the constraints of a int64 (by a factor of
2053      * about 29).
2054      *
2055      * If you actually hit the following assertion, probably you should file a
2056      * bug against your operating system for being excessively silly.
2057      **/
2058     g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2059               ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2060
2061     return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2062   }
2063 #else
2064   /* It may look like we are discarding accuracy on Windows (since its
2065    * current time is expressed in 100s of nanoseconds) but according to
2066    * many sources, the time is only updated 64 times per second, so
2067    * microsecond accuracy is more than enough.
2068    */
2069   {
2070     GTimeVal tv;
2071
2072     g_get_current_time (&tv);
2073
2074     return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2075   }
2076 #endif
2077 }
2078
2079 static void
2080 g_main_dispatch_free (gpointer dispatch)
2081 {
2082   g_slice_free (GMainDispatch, dispatch);
2083 }
2084
2085 /* Running the main loop */
2086
2087 static GMainDispatch *
2088 get_dispatch (void)
2089 {
2090   static GPrivate depth_private = G_PRIVATE_INIT (g_main_dispatch_free);
2091   GMainDispatch *dispatch;
2092
2093   dispatch = g_private_get (&depth_private);
2094
2095   if (!dispatch)
2096     {
2097       dispatch = g_slice_new0 (GMainDispatch);
2098       g_private_set (&depth_private, dispatch);
2099     }
2100
2101   return dispatch;
2102 }
2103
2104 /**
2105  * g_main_depth:
2106  *
2107  * Returns the depth of the stack of calls to
2108  * g_main_context_dispatch() on any #GMainContext in the current thread.
2109  *  That is, when called from the toplevel, it gives 0. When
2110  * called from within a callback from g_main_context_iteration()
2111  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
2112  * a callback to a recursive call to g_main_context_iteration(),
2113  * it returns 2. And so forth.
2114  *
2115  * This function is useful in a situation like the following:
2116  * Imagine an extremely simple "garbage collected" system.
2117  *
2118  * |[
2119  * static GList *free_list;
2120  * 
2121  * gpointer
2122  * allocate_memory (gsize size)
2123  * { 
2124  *   gpointer result = g_malloc (size);
2125  *   free_list = g_list_prepend (free_list, result);
2126  *   return result;
2127  * }
2128  * 
2129  * void
2130  * free_allocated_memory (void)
2131  * {
2132  *   GList *l;
2133  *   for (l = free_list; l; l = l->next);
2134  *     g_free (l->data);
2135  *   g_list_free (free_list);
2136  *   free_list = NULL;
2137  *  }
2138  * 
2139  * [...]
2140  * 
2141  * while (TRUE); 
2142  *  {
2143  *    g_main_context_iteration (NULL, TRUE);
2144  *    free_allocated_memory();
2145  *   }
2146  * ]|
2147  *
2148  * This works from an application, however, if you want to do the same
2149  * thing from a library, it gets more difficult, since you no longer
2150  * control the main loop. You might think you can simply use an idle
2151  * function to make the call to free_allocated_memory(), but that
2152  * doesn't work, since the idle function could be called from a
2153  * recursive callback. This can be fixed by using g_main_depth()
2154  *
2155  * |[
2156  * gpointer
2157  * allocate_memory (gsize size)
2158  * { 
2159  *   FreeListBlock *block = g_new (FreeListBlock, 1);
2160  *   block->mem = g_malloc (size);
2161  *   block->depth = g_main_depth ();   
2162  *   free_list = g_list_prepend (free_list, block);
2163  *   return block->mem;
2164  * }
2165  * 
2166  * void
2167  * free_allocated_memory (void)
2168  * {
2169  *   GList *l;
2170  *   
2171  *   int depth = g_main_depth ();
2172  *   for (l = free_list; l; );
2173  *     {
2174  *       GList *next = l->next;
2175  *       FreeListBlock *block = l->data;
2176  *       if (block->depth > depth)
2177  *         {
2178  *           g_free (block->mem);
2179  *           g_free (block);
2180  *           free_list = g_list_delete_link (free_list, l);
2181  *         }
2182  *               
2183  *       l = next;
2184  *     }
2185  *   }
2186  * ]|
2187  *
2188  * There is a temptation to use g_main_depth() to solve
2189  * problems with reentrancy. For instance, while waiting for data
2190  * to be received from the network in response to a menu item,
2191  * the menu item might be selected again. It might seem that
2192  * one could make the menu item's callback return immediately
2193  * and do nothing if g_main_depth() returns a value greater than 1.
2194  * However, this should be avoided since the user then sees selecting
2195  * the menu item do nothing. Furthermore, you'll find yourself adding
2196  * these checks all over your code, since there are doubtless many,
2197  * many things that the user could do. Instead, you can use the
2198  * following techniques:
2199  *
2200  * <orderedlist>
2201  *  <listitem>
2202  *   <para>
2203  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
2204  *     the user from interacting with elements while the main
2205  *     loop is recursing.
2206  *   </para>
2207  *  </listitem>
2208  *  <listitem>
2209  *   <para>
2210  *     Avoid main loop recursion in situations where you can't handle
2211  *     arbitrary  callbacks. Instead, structure your code so that you
2212  *     simply return to the main loop and then get called again when
2213  *     there is more work to do.
2214  *   </para>
2215  *  </listitem>
2216  * </orderedlist>
2217  * 
2218  * Return value: The main loop recursion level in the current thread
2219  **/
2220 int
2221 g_main_depth (void)
2222 {
2223   GMainDispatch *dispatch = get_dispatch ();
2224   return dispatch->depth;
2225 }
2226
2227 /**
2228  * g_main_current_source:
2229  *
2230  * Returns the currently firing source for this thread.
2231  * 
2232  * Return value: (transfer none): The currently firing source or %NULL.
2233  *
2234  * Since: 2.12
2235  */
2236 GSource *
2237 g_main_current_source (void)
2238 {
2239   GMainDispatch *dispatch = get_dispatch ();
2240   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2241 }
2242
2243 /**
2244  * g_source_is_destroyed:
2245  * @source: a #GSource
2246  *
2247  * Returns whether @source has been destroyed.
2248  *
2249  * This is important when you operate upon your objects 
2250  * from within idle handlers, but may have freed the object 
2251  * before the dispatch of your idle handler.
2252  *
2253  * |[
2254  * static gboolean 
2255  * idle_callback (gpointer data)
2256  * {
2257  *   SomeWidget *self = data;
2258  *    
2259  *   GDK_THREADS_ENTER (<!-- -->);
2260  *   /<!-- -->* do stuff with self *<!-- -->/
2261  *   self->idle_id = 0;
2262  *   GDK_THREADS_LEAVE (<!-- -->);
2263  *    
2264  *   return FALSE;
2265  * }
2266  *  
2267  * static void 
2268  * some_widget_do_stuff_later (SomeWidget *self)
2269  * {
2270  *   self->idle_id = g_idle_add (idle_callback, self);
2271  * }
2272  *  
2273  * static void 
2274  * some_widget_finalize (GObject *object)
2275  * {
2276  *   SomeWidget *self = SOME_WIDGET (object);
2277  *    
2278  *   if (self->idle_id)
2279  *     g_source_remove (self->idle_id);
2280  *    
2281  *   G_OBJECT_CLASS (parent_class)->finalize (object);
2282  * }
2283  * ]|
2284  *
2285  * This will fail in a multi-threaded application if the 
2286  * widget is destroyed before the idle handler fires due 
2287  * to the use after free in the callback. A solution, to 
2288  * this particular problem, is to check to if the source
2289  * has already been destroy within the callback.
2290  *
2291  * |[
2292  * static gboolean 
2293  * idle_callback (gpointer data)
2294  * {
2295  *   SomeWidget *self = data;
2296  *   
2297  *   GDK_THREADS_ENTER ();
2298  *   if (!g_source_is_destroyed (g_main_current_source ()))
2299  *     {
2300  *       /<!-- -->* do stuff with self *<!-- -->/
2301  *     }
2302  *   GDK_THREADS_LEAVE ();
2303  *   
2304  *   return FALSE;
2305  * }
2306  * ]|
2307  *
2308  * Return value: %TRUE if the source has been destroyed
2309  *
2310  * Since: 2.12
2311  */
2312 gboolean
2313 g_source_is_destroyed (GSource *source)
2314 {
2315   return SOURCE_DESTROYED (source);
2316 }
2317
2318 /* Temporarily remove all this source's file descriptors from the
2319  * poll(), so that if data comes available for one of the file descriptors
2320  * we don't continually spin in the poll()
2321  */
2322 /* HOLDS: source->context's lock */
2323 static void
2324 block_source (GSource *source)
2325 {
2326   GSList *tmp_list;
2327
2328   g_return_if_fail (!SOURCE_BLOCKED (source));
2329
2330   tmp_list = source->poll_fds;
2331   while (tmp_list)
2332     {
2333       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2334       tmp_list = tmp_list->next;
2335     }
2336 }
2337
2338 /* HOLDS: source->context's lock */
2339 static void
2340 unblock_source (GSource *source)
2341 {
2342   GSList *tmp_list;
2343   
2344   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2345   g_return_if_fail (!SOURCE_DESTROYED (source));
2346   
2347   tmp_list = source->poll_fds;
2348   while (tmp_list)
2349     {
2350       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2351       tmp_list = tmp_list->next;
2352     }
2353 }
2354
2355 /* HOLDS: context's lock */
2356 static void
2357 g_main_dispatch (GMainContext *context)
2358 {
2359   GMainDispatch *current = get_dispatch ();
2360   guint i;
2361
2362   for (i = 0; i < context->pending_dispatches->len; i++)
2363     {
2364       GSource *source = context->pending_dispatches->pdata[i];
2365
2366       context->pending_dispatches->pdata[i] = NULL;
2367       g_assert (source);
2368
2369       source->flags &= ~G_SOURCE_READY;
2370
2371       if (!SOURCE_DESTROYED (source))
2372         {
2373           gboolean was_in_call;
2374           gpointer user_data = NULL;
2375           GSourceFunc callback = NULL;
2376           GSourceCallbackFuncs *cb_funcs;
2377           gpointer cb_data;
2378           gboolean need_destroy;
2379
2380           gboolean (*dispatch) (GSource *,
2381                                 GSourceFunc,
2382                                 gpointer);
2383           GSList current_source_link;
2384
2385           dispatch = source->source_funcs->dispatch;
2386           cb_funcs = source->callback_funcs;
2387           cb_data = source->callback_data;
2388
2389           if (cb_funcs)
2390             cb_funcs->ref (cb_data);
2391           
2392           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2393             block_source (source);
2394           
2395           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2396           source->flags |= G_HOOK_FLAG_IN_CALL;
2397
2398           if (cb_funcs)
2399             cb_funcs->get (cb_data, source, &callback, &user_data);
2400
2401           UNLOCK_CONTEXT (context);
2402
2403           current->depth++;
2404           /* The on-stack allocation of the GSList is unconventional, but
2405            * we know that the lifetime of the link is bounded to this
2406            * function as the link is kept in a thread specific list and
2407            * not manipulated outside of this function and its descendants.
2408            * Avoiding the overhead of a g_slist_alloc() is useful as many
2409            * applications do little more than dispatch events.
2410            *
2411            * This is a performance hack - do not revert to g_slist_prepend()!
2412            */
2413           current_source_link.data = source;
2414           current_source_link.next = current->dispatching_sources;
2415           current->dispatching_sources = &current_source_link;
2416           need_destroy = ! dispatch (source,
2417                                      callback,
2418                                      user_data);
2419           g_assert (current->dispatching_sources == &current_source_link);
2420           current->dispatching_sources = current_source_link.next;
2421           current->depth--;
2422           
2423           if (cb_funcs)
2424             cb_funcs->unref (cb_data);
2425
2426           LOCK_CONTEXT (context);
2427           
2428           if (!was_in_call)
2429             source->flags &= ~G_HOOK_FLAG_IN_CALL;
2430
2431           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2432               !SOURCE_DESTROYED (source))
2433             unblock_source (source);
2434           
2435           /* Note: this depends on the fact that we can't switch
2436            * sources from one main context to another
2437            */
2438           if (need_destroy && !SOURCE_DESTROYED (source))
2439             {
2440               g_assert (source->context == context);
2441               g_source_destroy_internal (source, context, TRUE);
2442             }
2443         }
2444       
2445       SOURCE_UNREF (source, context);
2446     }
2447
2448   g_ptr_array_set_size (context->pending_dispatches, 0);
2449 }
2450
2451 /* Holds context's lock */
2452 static inline GSource *
2453 next_valid_source (GMainContext *context,
2454                    GSource      *source)
2455 {
2456   GSource *new_source = source ? source->next : context->source_list;
2457
2458   while (new_source)
2459     {
2460       if (!SOURCE_DESTROYED (new_source))
2461         {
2462           new_source->ref_count++;
2463           break;
2464         }
2465       
2466       new_source = new_source->next;
2467     }
2468
2469   if (source)
2470     SOURCE_UNREF (source, context);
2471           
2472   return new_source;
2473 }
2474
2475 /**
2476  * g_main_context_acquire:
2477  * @context: a #GMainContext
2478  * 
2479  * Tries to become the owner of the specified context.
2480  * If some other thread is the owner of the context,
2481  * returns %FALSE immediately. Ownership is properly
2482  * recursive: the owner can require ownership again
2483  * and will release ownership when g_main_context_release()
2484  * is called as many times as g_main_context_acquire().
2485  *
2486  * You must be the owner of a context before you
2487  * can call g_main_context_prepare(), g_main_context_query(),
2488  * g_main_context_check(), g_main_context_dispatch().
2489  * 
2490  * Return value: %TRUE if the operation succeeded, and
2491  *   this thread is now the owner of @context.
2492  **/
2493 gboolean 
2494 g_main_context_acquire (GMainContext *context)
2495 {
2496   gboolean result = FALSE;
2497   GThread *self = G_THREAD_SELF;
2498
2499   if (context == NULL)
2500     context = g_main_context_default ();
2501   
2502   LOCK_CONTEXT (context);
2503
2504   if (!context->owner)
2505     {
2506       context->owner = self;
2507       g_assert (context->owner_count == 0);
2508     }
2509
2510   if (context->owner == self)
2511     {
2512       context->owner_count++;
2513       result = TRUE;
2514     }
2515
2516   UNLOCK_CONTEXT (context); 
2517   
2518   return result;
2519 }
2520
2521 /**
2522  * g_main_context_release:
2523  * @context: a #GMainContext
2524  * 
2525  * Releases ownership of a context previously acquired by this thread
2526  * with g_main_context_acquire(). If the context was acquired multiple
2527  * times, the ownership will be released only when g_main_context_release()
2528  * is called as many times as it was acquired.
2529  **/
2530 void
2531 g_main_context_release (GMainContext *context)
2532 {
2533   if (context == NULL)
2534     context = g_main_context_default ();
2535   
2536   LOCK_CONTEXT (context);
2537
2538   context->owner_count--;
2539   if (context->owner_count == 0)
2540     {
2541       context->owner = NULL;
2542
2543       if (context->waiters)
2544         {
2545           GMainWaiter *waiter = context->waiters->data;
2546           gboolean loop_internal_waiter = (waiter->mutex == &context->mutex);
2547           context->waiters = g_slist_delete_link (context->waiters,
2548                                                   context->waiters);
2549           if (!loop_internal_waiter)
2550             g_mutex_lock (waiter->mutex);
2551           
2552           g_cond_signal (waiter->cond);
2553           
2554           if (!loop_internal_waiter)
2555             g_mutex_unlock (waiter->mutex);
2556         }
2557     }
2558
2559   UNLOCK_CONTEXT (context); 
2560 }
2561
2562 /**
2563  * g_main_context_wait:
2564  * @context: a #GMainContext
2565  * @cond: a condition variable
2566  * @mutex: a mutex, currently held
2567  * 
2568  * Tries to become the owner of the specified context,
2569  * as with g_main_context_acquire(). But if another thread
2570  * is the owner, atomically drop @mutex and wait on @cond until 
2571  * that owner releases ownership or until @cond is signaled, then
2572  * try again (once) to become the owner.
2573  * 
2574  * Return value: %TRUE if the operation succeeded, and
2575  *   this thread is now the owner of @context.
2576  **/
2577 gboolean
2578 g_main_context_wait (GMainContext *context,
2579                      GCond        *cond,
2580                      GMutex       *mutex)
2581 {
2582   gboolean result = FALSE;
2583   GThread *self = G_THREAD_SELF;
2584   gboolean loop_internal_waiter;
2585   
2586   if (context == NULL)
2587     context = g_main_context_default ();
2588
2589   loop_internal_waiter = (mutex == &context->mutex);
2590   
2591   if (!loop_internal_waiter)
2592     LOCK_CONTEXT (context);
2593
2594   if (context->owner && context->owner != self)
2595     {
2596       GMainWaiter waiter;
2597
2598       waiter.cond = cond;
2599       waiter.mutex = mutex;
2600
2601       context->waiters = g_slist_append (context->waiters, &waiter);
2602       
2603       if (!loop_internal_waiter)
2604         UNLOCK_CONTEXT (context);
2605       g_cond_wait (cond, mutex);
2606       if (!loop_internal_waiter)      
2607         LOCK_CONTEXT (context);
2608
2609       context->waiters = g_slist_remove (context->waiters, &waiter);
2610     }
2611
2612   if (!context->owner)
2613     {
2614       context->owner = self;
2615       g_assert (context->owner_count == 0);
2616     }
2617
2618   if (context->owner == self)
2619     {
2620       context->owner_count++;
2621       result = TRUE;
2622     }
2623
2624   if (!loop_internal_waiter)
2625     UNLOCK_CONTEXT (context); 
2626   
2627   return result;
2628 }
2629
2630 /**
2631  * g_main_context_prepare:
2632  * @context: a #GMainContext
2633  * @priority: location to store priority of highest priority
2634  *            source already ready.
2635  * 
2636  * Prepares to poll sources within a main loop. The resulting information
2637  * for polling is determined by calling g_main_context_query ().
2638  * 
2639  * Return value: %TRUE if some source is ready to be dispatched
2640  *               prior to polling.
2641  **/
2642 gboolean
2643 g_main_context_prepare (GMainContext *context,
2644                         gint         *priority)
2645 {
2646   gint i;
2647   gint n_ready = 0;
2648   gint current_priority = G_MAXINT;
2649   GSource *source;
2650
2651   if (context == NULL)
2652     context = g_main_context_default ();
2653   
2654   LOCK_CONTEXT (context);
2655
2656   context->time_is_fresh = FALSE;
2657
2658   if (context->in_check_or_prepare)
2659     {
2660       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2661                  "prepare() member.");
2662       UNLOCK_CONTEXT (context);
2663       return FALSE;
2664     }
2665
2666 #if 0
2667   /* If recursing, finish up current dispatch, before starting over */
2668   if (context->pending_dispatches)
2669     {
2670       if (dispatch)
2671         g_main_dispatch (context, &current_time);
2672       
2673       UNLOCK_CONTEXT (context);
2674       return TRUE;
2675     }
2676 #endif
2677
2678   /* If recursing, clear list of pending dispatches */
2679
2680   for (i = 0; i < context->pending_dispatches->len; i++)
2681     {
2682       if (context->pending_dispatches->pdata[i])
2683         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2684     }
2685   g_ptr_array_set_size (context->pending_dispatches, 0);
2686   
2687   /* Prepare all sources */
2688
2689   context->timeout = -1;
2690   
2691   source = next_valid_source (context, NULL);
2692   while (source)
2693     {
2694       gint source_timeout = -1;
2695
2696       if ((n_ready > 0) && (source->priority > current_priority))
2697         {
2698           SOURCE_UNREF (source, context);
2699           break;
2700         }
2701       if (SOURCE_BLOCKED (source))
2702         goto next;
2703
2704       if (!(source->flags & G_SOURCE_READY))
2705         {
2706           gboolean result;
2707           gboolean (*prepare)  (GSource  *source, 
2708                                 gint     *timeout);
2709
2710           prepare = source->source_funcs->prepare;
2711           context->in_check_or_prepare++;
2712           UNLOCK_CONTEXT (context);
2713
2714           result = (*prepare) (source, &source_timeout);
2715
2716           LOCK_CONTEXT (context);
2717           context->in_check_or_prepare--;
2718
2719           if (result)
2720             {
2721               GSource *ready_source = source;
2722
2723               while (ready_source)
2724                 {
2725                   ready_source->flags |= G_SOURCE_READY;
2726                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2727                 }
2728             }
2729         }
2730
2731       if (source->flags & G_SOURCE_READY)
2732         {
2733           n_ready++;
2734           current_priority = source->priority;
2735           context->timeout = 0;
2736         }
2737       
2738       if (source_timeout >= 0)
2739         {
2740           if (context->timeout < 0)
2741             context->timeout = source_timeout;
2742           else
2743             context->timeout = MIN (context->timeout, source_timeout);
2744         }
2745
2746     next:
2747       source = next_valid_source (context, source);
2748     }
2749
2750   UNLOCK_CONTEXT (context);
2751   
2752   if (priority)
2753     *priority = current_priority;
2754   
2755   return (n_ready > 0);
2756 }
2757
2758 /**
2759  * g_main_context_query:
2760  * @context: a #GMainContext
2761  * @max_priority: maximum priority source to check
2762  * @timeout_: (out): location to store timeout to be used in polling
2763  * @fds: (out caller-allocates) (array length=n_fds): location to
2764  *       store #GPollFD records that need to be polled.
2765  * @n_fds: length of @fds.
2766  * 
2767  * Determines information necessary to poll this main loop.
2768  * 
2769  * Return value: the number of records actually stored in @fds,
2770  *   or, if more than @n_fds records need to be stored, the number
2771  *   of records that need to be stored.
2772  **/
2773 gint
2774 g_main_context_query (GMainContext *context,
2775                       gint          max_priority,
2776                       gint         *timeout,
2777                       GPollFD      *fds,
2778                       gint          n_fds)
2779 {
2780   gint n_poll;
2781   GPollRec *pollrec;
2782   
2783   LOCK_CONTEXT (context);
2784
2785   pollrec = context->poll_records;
2786   n_poll = 0;
2787   while (pollrec && max_priority >= pollrec->priority)
2788     {
2789       /* We need to include entries with fd->events == 0 in the array because
2790        * otherwise if the application changes fd->events behind our back and 
2791        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2792        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2793        * this API, but it occurs in practice.) */
2794       if (n_poll < n_fds)
2795         {
2796           fds[n_poll].fd = pollrec->fd->fd;
2797           /* In direct contradiction to the Unix98 spec, IRIX runs into
2798            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2799            * flags in the events field of the pollfd while it should
2800            * just ignoring them. So we mask them out here.
2801            */
2802           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2803           fds[n_poll].revents = 0;
2804         }
2805
2806       pollrec = pollrec->next;
2807       n_poll++;
2808     }
2809
2810   context->poll_changed = FALSE;
2811   
2812   if (timeout)
2813     {
2814       *timeout = context->timeout;
2815       if (*timeout != 0)
2816         context->time_is_fresh = FALSE;
2817     }
2818   
2819   UNLOCK_CONTEXT (context);
2820
2821   return n_poll;
2822 }
2823
2824 /**
2825  * g_main_context_check:
2826  * @context: a #GMainContext
2827  * @max_priority: the maximum numerical priority of sources to check
2828  * @fds: (array length=n_fds): array of #GPollFD's that was passed to
2829  *       the last call to g_main_context_query()
2830  * @n_fds: return value of g_main_context_query()
2831  * 
2832  * Passes the results of polling back to the main loop.
2833  * 
2834  * Return value: %TRUE if some sources are ready to be dispatched.
2835  **/
2836 gboolean
2837 g_main_context_check (GMainContext *context,
2838                       gint          max_priority,
2839                       GPollFD      *fds,
2840                       gint          n_fds)
2841 {
2842   GSource *source;
2843   GPollRec *pollrec;
2844   gint n_ready = 0;
2845   gint i;
2846    
2847   LOCK_CONTEXT (context);
2848
2849   if (context->in_check_or_prepare)
2850     {
2851       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2852                  "prepare() member.");
2853       UNLOCK_CONTEXT (context);
2854       return FALSE;
2855     }
2856
2857   if (context->wake_up_rec.events)
2858     g_wakeup_acknowledge (context->wakeup);
2859
2860   /* If the set of poll file descriptors changed, bail out
2861    * and let the main loop rerun
2862    */
2863   if (context->poll_changed)
2864     {
2865       UNLOCK_CONTEXT (context);
2866       return FALSE;
2867     }
2868   
2869   pollrec = context->poll_records;
2870   i = 0;
2871   while (i < n_fds)
2872     {
2873       if (pollrec->fd->events)
2874         pollrec->fd->revents = fds[i].revents;
2875
2876       pollrec = pollrec->next;
2877       i++;
2878     }
2879
2880   source = next_valid_source (context, NULL);
2881   while (source)
2882     {
2883       if ((n_ready > 0) && (source->priority > max_priority))
2884         {
2885           SOURCE_UNREF (source, context);
2886           break;
2887         }
2888       if (SOURCE_BLOCKED (source))
2889         goto next;
2890
2891       if (!(source->flags & G_SOURCE_READY))
2892         {
2893           gboolean result;
2894           gboolean (*check) (GSource  *source);
2895
2896           check = source->source_funcs->check;
2897           
2898           context->in_check_or_prepare++;
2899           UNLOCK_CONTEXT (context);
2900           
2901           result = (*check) (source);
2902           
2903           LOCK_CONTEXT (context);
2904           context->in_check_or_prepare--;
2905           
2906           if (result)
2907             {
2908               GSource *ready_source = source;
2909
2910               while (ready_source)
2911                 {
2912                   ready_source->flags |= G_SOURCE_READY;
2913                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2914                 }
2915             }
2916         }
2917
2918       if (source->flags & G_SOURCE_READY)
2919         {
2920           source->ref_count++;
2921           g_ptr_array_add (context->pending_dispatches, source);
2922
2923           n_ready++;
2924
2925           /* never dispatch sources with less priority than the first
2926            * one we choose to dispatch
2927            */
2928           max_priority = source->priority;
2929         }
2930
2931     next:
2932       source = next_valid_source (context, source);
2933     }
2934
2935   UNLOCK_CONTEXT (context);
2936
2937   return n_ready > 0;
2938 }
2939
2940 /**
2941  * g_main_context_dispatch:
2942  * @context: a #GMainContext
2943  * 
2944  * Dispatches all pending sources.
2945  **/
2946 void
2947 g_main_context_dispatch (GMainContext *context)
2948 {
2949   LOCK_CONTEXT (context);
2950
2951   if (context->pending_dispatches->len > 0)
2952     {
2953       g_main_dispatch (context);
2954     }
2955
2956   UNLOCK_CONTEXT (context);
2957 }
2958
2959 /* HOLDS context lock */
2960 static gboolean
2961 g_main_context_iterate (GMainContext *context,
2962                         gboolean      block,
2963                         gboolean      dispatch,
2964                         GThread      *self)
2965 {
2966   gint max_priority;
2967   gint timeout;
2968   gboolean some_ready;
2969   gint nfds, allocated_nfds;
2970   GPollFD *fds = NULL;
2971
2972   UNLOCK_CONTEXT (context);
2973
2974   if (!g_main_context_acquire (context))
2975     {
2976       gboolean got_ownership;
2977
2978       LOCK_CONTEXT (context);
2979
2980       if (!block)
2981         return FALSE;
2982
2983       got_ownership = g_main_context_wait (context,
2984                                            &context->cond,
2985                                            &context->mutex);
2986
2987       if (!got_ownership)
2988         return FALSE;
2989     }
2990   else
2991     LOCK_CONTEXT (context);
2992   
2993   if (!context->cached_poll_array)
2994     {
2995       context->cached_poll_array_size = context->n_poll_records;
2996       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2997     }
2998
2999   allocated_nfds = context->cached_poll_array_size;
3000   fds = context->cached_poll_array;
3001   
3002   UNLOCK_CONTEXT (context);
3003
3004   g_main_context_prepare (context, &max_priority); 
3005   
3006   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
3007                                        allocated_nfds)) > allocated_nfds)
3008     {
3009       LOCK_CONTEXT (context);
3010       g_free (fds);
3011       context->cached_poll_array_size = allocated_nfds = nfds;
3012       context->cached_poll_array = fds = g_new (GPollFD, nfds);
3013       UNLOCK_CONTEXT (context);
3014     }
3015
3016   if (!block)
3017     timeout = 0;
3018   
3019   g_assert (!g_main_context_fork_detected);
3020   g_main_context_poll (context, timeout, max_priority, fds, nfds);
3021   
3022   some_ready = g_main_context_check (context, max_priority, fds, nfds);
3023   
3024   if (dispatch)
3025     g_main_context_dispatch (context);
3026   
3027   g_main_context_release (context);
3028
3029   LOCK_CONTEXT (context);
3030
3031   return some_ready;
3032 }
3033
3034 /**
3035  * g_main_context_pending:
3036  * @context: a #GMainContext (if %NULL, the default context will be used)
3037  *
3038  * Checks if any sources have pending events for the given context.
3039  * 
3040  * Return value: %TRUE if events are pending.
3041  **/
3042 gboolean 
3043 g_main_context_pending (GMainContext *context)
3044 {
3045   gboolean retval;
3046
3047   if (!context)
3048     context = g_main_context_default();
3049
3050   LOCK_CONTEXT (context);
3051   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3052   UNLOCK_CONTEXT (context);
3053   
3054   return retval;
3055 }
3056
3057 /**
3058  * g_main_context_iteration:
3059  * @context: a #GMainContext (if %NULL, the default context will be used) 
3060  * @may_block: whether the call may block.
3061  * 
3062  * Runs a single iteration for the given main loop. This involves
3063  * checking to see if any event sources are ready to be processed,
3064  * then if no events sources are ready and @may_block is %TRUE, waiting
3065  * for a source to become ready, then dispatching the highest priority
3066  * events sources that are ready. Otherwise, if @may_block is %FALSE 
3067  * sources are not waited to become ready, only those highest priority 
3068  * events sources will be dispatched (if any), that are ready at this 
3069  * given moment without further waiting.
3070  *
3071  * Note that even when @may_block is %TRUE, it is still possible for 
3072  * g_main_context_iteration() to return %FALSE, since the the wait may 
3073  * be interrupted for other reasons than an event source becoming ready.
3074  * 
3075  * Return value: %TRUE if events were dispatched.
3076  **/
3077 gboolean
3078 g_main_context_iteration (GMainContext *context, gboolean may_block)
3079 {
3080   gboolean retval;
3081
3082   if (!context)
3083     context = g_main_context_default();
3084   
3085   LOCK_CONTEXT (context);
3086   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3087   UNLOCK_CONTEXT (context);
3088   
3089   return retval;
3090 }
3091
3092 /**
3093  * g_main_loop_new:
3094  * @context: (allow-none): a #GMainContext  (if %NULL, the default context will be used).
3095  * @is_running: set to %TRUE to indicate that the loop is running. This
3096  * is not very important since calling g_main_loop_run() will set this to
3097  * %TRUE anyway.
3098  * 
3099  * Creates a new #GMainLoop structure.
3100  * 
3101  * Return value: a new #GMainLoop.
3102  **/
3103 GMainLoop *
3104 g_main_loop_new (GMainContext *context,
3105                  gboolean      is_running)
3106 {
3107   GMainLoop *loop;
3108
3109   if (!context)
3110     context = g_main_context_default();
3111   
3112   g_main_context_ref (context);
3113
3114   loop = g_new0 (GMainLoop, 1);
3115   loop->context = context;
3116   loop->is_running = is_running != FALSE;
3117   loop->ref_count = 1;
3118   
3119   return loop;
3120 }
3121
3122 /**
3123  * g_main_loop_ref:
3124  * @loop: a #GMainLoop
3125  * 
3126  * Increases the reference count on a #GMainLoop object by one.
3127  * 
3128  * Return value: @loop
3129  **/
3130 GMainLoop *
3131 g_main_loop_ref (GMainLoop *loop)
3132 {
3133   g_return_val_if_fail (loop != NULL, NULL);
3134   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3135
3136   g_atomic_int_inc (&loop->ref_count);
3137
3138   return loop;
3139 }
3140
3141 /**
3142  * g_main_loop_unref:
3143  * @loop: a #GMainLoop
3144  * 
3145  * Decreases the reference count on a #GMainLoop object by one. If
3146  * the result is zero, free the loop and free all associated memory.
3147  **/
3148 void
3149 g_main_loop_unref (GMainLoop *loop)
3150 {
3151   g_return_if_fail (loop != NULL);
3152   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3153
3154   if (!g_atomic_int_dec_and_test (&loop->ref_count))
3155     return;
3156
3157   g_main_context_unref (loop->context);
3158   g_free (loop);
3159 }
3160
3161 /**
3162  * g_main_loop_run:
3163  * @loop: a #GMainLoop
3164  * 
3165  * Runs a main loop until g_main_loop_quit() is called on the loop.
3166  * If this is called for the thread of the loop's #GMainContext,
3167  * it will process events from the loop, otherwise it will
3168  * simply wait.
3169  **/
3170 void 
3171 g_main_loop_run (GMainLoop *loop)
3172 {
3173   GThread *self = G_THREAD_SELF;
3174
3175   g_return_if_fail (loop != NULL);
3176   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3177
3178   if (!g_main_context_acquire (loop->context))
3179     {
3180       gboolean got_ownership = FALSE;
3181       
3182       /* Another thread owns this context */
3183       LOCK_CONTEXT (loop->context);
3184
3185       g_atomic_int_inc (&loop->ref_count);
3186
3187       if (!loop->is_running)
3188         loop->is_running = TRUE;
3189
3190       while (loop->is_running && !got_ownership)
3191         got_ownership = g_main_context_wait (loop->context,
3192                                              &loop->context->cond,
3193                                              &loop->context->mutex);
3194       
3195       if (!loop->is_running)
3196         {
3197           UNLOCK_CONTEXT (loop->context);
3198           if (got_ownership)
3199             g_main_context_release (loop->context);
3200           g_main_loop_unref (loop);
3201           return;
3202         }
3203
3204       g_assert (got_ownership);
3205     }
3206   else
3207     LOCK_CONTEXT (loop->context);
3208
3209   if (loop->context->in_check_or_prepare)
3210     {
3211       g_warning ("g_main_loop_run(): called recursively from within a source's "
3212                  "check() or prepare() member, iteration not possible.");
3213       return;
3214     }
3215
3216   g_atomic_int_inc (&loop->ref_count);
3217   loop->is_running = TRUE;
3218   while (loop->is_running)
3219     g_main_context_iterate (loop->context, TRUE, TRUE, self);
3220
3221   UNLOCK_CONTEXT (loop->context);
3222   
3223   g_main_context_release (loop->context);
3224   
3225   g_main_loop_unref (loop);
3226 }
3227
3228 /**
3229  * g_main_loop_quit:
3230  * @loop: a #GMainLoop
3231  * 
3232  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3233  * for the loop will return. 
3234  *
3235  * Note that sources that have already been dispatched when 
3236  * g_main_loop_quit() is called will still be executed.
3237  **/
3238 void 
3239 g_main_loop_quit (GMainLoop *loop)
3240 {
3241   g_return_if_fail (loop != NULL);
3242   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3243
3244   LOCK_CONTEXT (loop->context);
3245   loop->is_running = FALSE;
3246   g_wakeup_signal (loop->context->wakeup);
3247
3248   g_cond_broadcast (&loop->context->cond);
3249
3250   UNLOCK_CONTEXT (loop->context);
3251 }
3252
3253 /**
3254  * g_main_loop_is_running:
3255  * @loop: a #GMainLoop.
3256  * 
3257  * Checks to see if the main loop is currently being run via g_main_loop_run().
3258  * 
3259  * Return value: %TRUE if the mainloop is currently being run.
3260  **/
3261 gboolean
3262 g_main_loop_is_running (GMainLoop *loop)
3263 {
3264   g_return_val_if_fail (loop != NULL, FALSE);
3265   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3266
3267   return loop->is_running;
3268 }
3269
3270 /**
3271  * g_main_loop_get_context:
3272  * @loop: a #GMainLoop.
3273  * 
3274  * Returns the #GMainContext of @loop.
3275  * 
3276  * Return value: (transfer none): the #GMainContext of @loop
3277  **/
3278 GMainContext *
3279 g_main_loop_get_context (GMainLoop *loop)
3280 {
3281   g_return_val_if_fail (loop != NULL, NULL);
3282   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3283  
3284   return loop->context;
3285 }
3286
3287 /* HOLDS: context's lock */
3288 static void
3289 g_main_context_poll (GMainContext *context,
3290                      gint          timeout,
3291                      gint          priority,
3292                      GPollFD      *fds,
3293                      gint          n_fds)
3294 {
3295 #ifdef  G_MAIN_POLL_DEBUG
3296   GTimer *poll_timer;
3297   GPollRec *pollrec;
3298   gint i;
3299 #endif
3300
3301   GPollFunc poll_func;
3302
3303   if (n_fds || timeout != 0)
3304     {
3305 #ifdef  G_MAIN_POLL_DEBUG
3306       if (_g_main_poll_debug)
3307         {
3308           g_print ("polling context=%p n=%d timeout=%d\n",
3309                    context, n_fds, timeout);
3310           poll_timer = g_timer_new ();
3311         }
3312 #endif
3313
3314       LOCK_CONTEXT (context);
3315
3316       poll_func = context->poll_func;
3317       
3318       UNLOCK_CONTEXT (context);
3319       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3320         {
3321 #ifndef G_OS_WIN32
3322           g_warning ("poll(2) failed due to: %s.",
3323                      g_strerror (errno));
3324 #else
3325           /* If g_poll () returns -1, it has already called g_warning() */
3326 #endif
3327         }
3328       
3329 #ifdef  G_MAIN_POLL_DEBUG
3330       if (_g_main_poll_debug)
3331         {
3332           LOCK_CONTEXT (context);
3333
3334           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3335                    n_fds,
3336                    timeout,
3337                    g_timer_elapsed (poll_timer, NULL));
3338           g_timer_destroy (poll_timer);
3339           pollrec = context->poll_records;
3340
3341           while (pollrec != NULL)
3342             {
3343               i = 0;
3344               while (i < n_fds)
3345                 {
3346                   if (fds[i].fd == pollrec->fd->fd &&
3347                       pollrec->fd->events &&
3348                       fds[i].revents)
3349                     {
3350                       g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3351                       if (fds[i].revents & G_IO_IN)
3352                         g_print ("i");
3353                       if (fds[i].revents & G_IO_OUT)
3354                         g_print ("o");
3355                       if (fds[i].revents & G_IO_PRI)
3356                         g_print ("p");
3357                       if (fds[i].revents & G_IO_ERR)
3358                         g_print ("e");
3359                       if (fds[i].revents & G_IO_HUP)
3360                         g_print ("h");
3361                       if (fds[i].revents & G_IO_NVAL)
3362                         g_print ("n");
3363                       g_print ("]");
3364                     }
3365                   i++;
3366                 }
3367               pollrec = pollrec->next;
3368             }
3369           g_print ("\n");
3370
3371           UNLOCK_CONTEXT (context);
3372         }
3373 #endif
3374     } /* if (n_fds || timeout != 0) */
3375 }
3376
3377 /**
3378  * g_main_context_add_poll:
3379  * @context: a #GMainContext (or %NULL for the default context)
3380  * @fd: a #GPollFD structure holding information about a file
3381  *      descriptor to watch.
3382  * @priority: the priority for this file descriptor which should be
3383  *      the same as the priority used for g_source_attach() to ensure that the
3384  *      file descriptor is polled whenever the results may be needed.
3385  * 
3386  * Adds a file descriptor to the set of file descriptors polled for
3387  * this context. This will very seldom be used directly. Instead
3388  * a typical event source will use g_source_add_poll() instead.
3389  **/
3390 void
3391 g_main_context_add_poll (GMainContext *context,
3392                          GPollFD      *fd,
3393                          gint          priority)
3394 {
3395   if (!context)
3396     context = g_main_context_default ();
3397   
3398   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3399   g_return_if_fail (fd);
3400
3401   LOCK_CONTEXT (context);
3402   g_main_context_add_poll_unlocked (context, priority, fd);
3403   UNLOCK_CONTEXT (context);
3404 }
3405
3406 /* HOLDS: main_loop_lock */
3407 static void 
3408 g_main_context_add_poll_unlocked (GMainContext *context,
3409                                   gint          priority,
3410                                   GPollFD      *fd)
3411 {
3412   GPollRec *prevrec, *nextrec;
3413   GPollRec *newrec = g_slice_new (GPollRec);
3414
3415   /* This file descriptor may be checked before we ever poll */
3416   fd->revents = 0;
3417   newrec->fd = fd;
3418   newrec->priority = priority;
3419
3420   prevrec = context->poll_records_tail;
3421   nextrec = NULL;
3422   while (prevrec && priority < prevrec->priority)
3423     {
3424       nextrec = prevrec;
3425       prevrec = prevrec->prev;
3426     }
3427
3428   if (prevrec)
3429     prevrec->next = newrec;
3430   else
3431     context->poll_records = newrec;
3432
3433   newrec->prev = prevrec;
3434   newrec->next = nextrec;
3435
3436   if (nextrec)
3437     nextrec->prev = newrec;
3438   else 
3439     context->poll_records_tail = newrec;
3440
3441   context->n_poll_records++;
3442
3443   context->poll_changed = TRUE;
3444
3445   /* Now wake up the main loop if it is waiting in the poll() */
3446   g_wakeup_signal (context->wakeup);
3447 }
3448
3449 /**
3450  * g_main_context_remove_poll:
3451  * @context:a #GMainContext 
3452  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3453  * 
3454  * Removes file descriptor from the set of file descriptors to be
3455  * polled for a particular context.
3456  **/
3457 void
3458 g_main_context_remove_poll (GMainContext *context,
3459                             GPollFD      *fd)
3460 {
3461   if (!context)
3462     context = g_main_context_default ();
3463   
3464   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3465   g_return_if_fail (fd);
3466
3467   LOCK_CONTEXT (context);
3468   g_main_context_remove_poll_unlocked (context, fd);
3469   UNLOCK_CONTEXT (context);
3470 }
3471
3472 static void
3473 g_main_context_remove_poll_unlocked (GMainContext *context,
3474                                      GPollFD      *fd)
3475 {
3476   GPollRec *pollrec, *prevrec, *nextrec;
3477
3478   prevrec = NULL;
3479   pollrec = context->poll_records;
3480
3481   while (pollrec)
3482     {
3483       nextrec = pollrec->next;
3484       if (pollrec->fd == fd)
3485         {
3486           if (prevrec != NULL)
3487             prevrec->next = nextrec;
3488           else
3489             context->poll_records = nextrec;
3490
3491           if (nextrec != NULL)
3492             nextrec->prev = prevrec;
3493           else
3494             context->poll_records_tail = prevrec;
3495
3496           g_slice_free (GPollRec, pollrec);
3497
3498           context->n_poll_records--;
3499           break;
3500         }
3501       prevrec = pollrec;
3502       pollrec = nextrec;
3503     }
3504
3505   context->poll_changed = TRUE;
3506   
3507   /* Now wake up the main loop if it is waiting in the poll() */
3508   g_wakeup_signal (context->wakeup);
3509 }
3510
3511 /**
3512  * g_source_get_current_time:
3513  * @source:  a #GSource
3514  * @timeval: #GTimeVal structure in which to store current time.
3515  *
3516  * This function ignores @source and is otherwise the same as
3517  * g_get_current_time().
3518  *
3519  * Deprecated: 2.28: use g_source_get_time() instead
3520  **/
3521 void
3522 g_source_get_current_time (GSource  *source,
3523                            GTimeVal *timeval)
3524 {
3525   g_get_current_time (timeval);
3526 }
3527
3528 /**
3529  * g_source_get_time:
3530  * @source: a #GSource
3531  *
3532  * Gets the time to be used when checking this source. The advantage of
3533  * calling this function over calling g_get_monotonic_time() directly is
3534  * that when checking multiple sources, GLib can cache a single value
3535  * instead of having to repeatedly get the system monotonic time.
3536  *
3537  * The time here is the system monotonic time, if available, or some
3538  * other reasonable alternative otherwise.  See g_get_monotonic_time().
3539  *
3540  * Returns: the monotonic time in microseconds
3541  *
3542  * Since: 2.28
3543  **/
3544 gint64
3545 g_source_get_time (GSource *source)
3546 {
3547   GMainContext *context;
3548   gint64 result;
3549
3550   g_return_val_if_fail (source->context != NULL, 0);
3551
3552   context = source->context;
3553
3554   LOCK_CONTEXT (context);
3555
3556   if (!context->time_is_fresh)
3557     {
3558       context->time = g_get_monotonic_time ();
3559       context->time_is_fresh = TRUE;
3560     }
3561
3562   result = context->time;
3563
3564   UNLOCK_CONTEXT (context);
3565
3566   return result;
3567 }
3568
3569 /**
3570  * g_main_context_set_poll_func:
3571  * @context: a #GMainContext
3572  * @func: the function to call to poll all file descriptors
3573  * 
3574  * Sets the function to use to handle polling of file descriptors. It
3575  * will be used instead of the poll() system call 
3576  * (or GLib's replacement function, which is used where 
3577  * poll() isn't available).
3578  *
3579  * This function could possibly be used to integrate the GLib event
3580  * loop with an external event loop.
3581  **/
3582 void
3583 g_main_context_set_poll_func (GMainContext *context,
3584                               GPollFunc     func)
3585 {
3586   if (!context)
3587     context = g_main_context_default ();
3588   
3589   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3590
3591   LOCK_CONTEXT (context);
3592   
3593   if (func)
3594     context->poll_func = func;
3595   else
3596     context->poll_func = g_poll;
3597
3598   UNLOCK_CONTEXT (context);
3599 }
3600
3601 /**
3602  * g_main_context_get_poll_func:
3603  * @context: a #GMainContext
3604  * 
3605  * Gets the poll function set by g_main_context_set_poll_func().
3606  * 
3607  * Return value: the poll function
3608  **/
3609 GPollFunc
3610 g_main_context_get_poll_func (GMainContext *context)
3611 {
3612   GPollFunc result;
3613   
3614   if (!context)
3615     context = g_main_context_default ();
3616   
3617   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3618
3619   LOCK_CONTEXT (context);
3620   result = context->poll_func;
3621   UNLOCK_CONTEXT (context);
3622
3623   return result;
3624 }
3625
3626 /**
3627  * g_main_context_wakeup:
3628  * @context: a #GMainContext
3629  * 
3630  * If @context is currently waiting in a poll(), interrupt
3631  * the poll(), and continue the iteration process.
3632  **/
3633 void
3634 g_main_context_wakeup (GMainContext *context)
3635 {
3636   if (!context)
3637     context = g_main_context_default ();
3638
3639   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3640
3641   g_wakeup_signal (context->wakeup);
3642 }
3643
3644 /**
3645  * g_main_context_is_owner:
3646  * @context: a #GMainContext
3647  * 
3648  * Determines whether this thread holds the (recursive)
3649  * ownership of this #GMainContext. This is useful to
3650  * know before waiting on another thread that may be
3651  * blocking to get ownership of @context.
3652  *
3653  * Returns: %TRUE if current thread is owner of @context.
3654  *
3655  * Since: 2.10
3656  **/
3657 gboolean
3658 g_main_context_is_owner (GMainContext *context)
3659 {
3660   gboolean is_owner;
3661
3662   if (!context)
3663     context = g_main_context_default ();
3664
3665   LOCK_CONTEXT (context);
3666   is_owner = context->owner == G_THREAD_SELF;
3667   UNLOCK_CONTEXT (context);
3668
3669   return is_owner;
3670 }
3671
3672 /* Timeouts */
3673
3674 static void
3675 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3676                           gint64          current_time)
3677 {
3678   timeout_source->expiration = current_time +
3679                                (guint64) timeout_source->interval * 1000;
3680
3681   if (timeout_source->seconds)
3682     {
3683       gint64 remainder;
3684       static gint timer_perturb = -1;
3685
3686       if (timer_perturb == -1)
3687         {
3688           /*
3689            * we want a per machine/session unique 'random' value; try the dbus
3690            * address first, that has a UUID in it. If there is no dbus, use the
3691            * hostname for hashing.
3692            */
3693           const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3694           if (!session_bus_address)
3695             session_bus_address = g_getenv ("HOSTNAME");
3696           if (session_bus_address)
3697             timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3698           else
3699             timer_perturb = 0;
3700         }
3701
3702       /* We want the microseconds part of the timeout to land on the
3703        * 'timer_perturb' mark, but we need to make sure we don't try to
3704        * set the timeout in the past.  We do this by ensuring that we
3705        * always only *increase* the expiration time by adding a full
3706        * second in the case that the microsecond portion decreases.
3707        */
3708       timeout_source->expiration -= timer_perturb;
3709
3710       remainder = timeout_source->expiration % 1000000;
3711       if (remainder >= 1000000/4)
3712         timeout_source->expiration += 1000000;
3713
3714       timeout_source->expiration -= remainder;
3715       timeout_source->expiration += timer_perturb;
3716     }
3717 }
3718
3719 static gboolean
3720 g_timeout_prepare (GSource *source,
3721                    gint    *timeout)
3722 {
3723   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3724   gint64 now = g_source_get_time (source);
3725
3726   if (now < timeout_source->expiration)
3727     {
3728       /* Round up to ensure that we don't try again too early */
3729       *timeout = (timeout_source->expiration - now + 999) / 1000;
3730       return FALSE;
3731     }
3732
3733   *timeout = 0;
3734   return TRUE;
3735 }
3736
3737 static gboolean 
3738 g_timeout_check (GSource *source)
3739 {
3740   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3741   gint64 now = g_source_get_time (source);
3742
3743   return timeout_source->expiration <= now;
3744 }
3745
3746 static gboolean
3747 g_timeout_dispatch (GSource     *source,
3748                     GSourceFunc  callback,
3749                     gpointer     user_data)
3750 {
3751   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3752   gboolean again;
3753
3754   if (!callback)
3755     {
3756       g_warning ("Timeout source dispatched without callback\n"
3757                  "You must call g_source_set_callback().");
3758       return FALSE;
3759     }
3760
3761   again = callback (user_data);
3762
3763   if (again)
3764     g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3765
3766   return again;
3767 }
3768
3769 /**
3770  * g_timeout_source_new:
3771  * @interval: the timeout interval in milliseconds.
3772  * 
3773  * Creates a new timeout source.
3774  *
3775  * The source will not initially be associated with any #GMainContext
3776  * and must be added to one with g_source_attach() before it will be
3777  * executed.
3778  *
3779  * The interval given is in terms of monotonic time, not wall clock
3780  * time.  See g_get_monotonic_time().
3781  * 
3782  * Return value: the newly-created timeout source
3783  **/
3784 GSource *
3785 g_timeout_source_new (guint interval)
3786 {
3787   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3788   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3789
3790   timeout_source->interval = interval;
3791   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3792
3793   return source;
3794 }
3795
3796 /**
3797  * g_timeout_source_new_seconds:
3798  * @interval: the timeout interval in seconds
3799  *
3800  * Creates a new timeout source.
3801  *
3802  * The source will not initially be associated with any #GMainContext
3803  * and must be added to one with g_source_attach() before it will be
3804  * executed.
3805  *
3806  * The scheduling granularity/accuracy of this timeout source will be
3807  * in seconds.
3808  *
3809  * The interval given in terms of monotonic time, not wall clock time.
3810  * See g_get_monotonic_time().
3811  *
3812  * Return value: the newly-created timeout source
3813  *
3814  * Since: 2.14  
3815  **/
3816 GSource *
3817 g_timeout_source_new_seconds (guint interval)
3818 {
3819   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3820   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3821
3822   timeout_source->interval = 1000 * interval;
3823   timeout_source->seconds = TRUE;
3824
3825   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3826
3827   return source;
3828 }
3829
3830
3831 /**
3832  * g_timeout_add_full:
3833  * @priority: the priority of the timeout source. Typically this will be in
3834  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3835  * @interval: the time between calls to the function, in milliseconds
3836  *             (1/1000ths of a second)
3837  * @function: function to call
3838  * @data:     data to pass to @function
3839  * @notify:   function to call when the timeout is removed, or %NULL
3840  * 
3841  * Sets a function to be called at regular intervals, with the given
3842  * priority.  The function is called repeatedly until it returns
3843  * %FALSE, at which point the timeout is automatically destroyed and
3844  * the function will not be called again.  The @notify function is
3845  * called when the timeout is destroyed.  The first call to the
3846  * function will be at the end of the first @interval.
3847  *
3848  * Note that timeout functions may be delayed, due to the processing of other
3849  * event sources. Thus they should not be relied on for precise timing.
3850  * After each call to the timeout function, the time of the next
3851  * timeout is recalculated based on the current time and the given interval
3852  * (it does not try to 'catch up' time lost in delays).
3853  *
3854  * This internally creates a main loop source using g_timeout_source_new()
3855  * and attaches it to the main loop context using g_source_attach(). You can
3856  * do these steps manually if you need greater control.
3857  *
3858  * The interval given in terms of monotonic time, not wall clock time.
3859  * See g_get_monotonic_time().
3860  * 
3861  * Return value: the ID (greater than 0) of the event source.
3862  * Rename to: g_timeout_add
3863  **/
3864 guint
3865 g_timeout_add_full (gint           priority,
3866                     guint          interval,
3867                     GSourceFunc    function,
3868                     gpointer       data,
3869                     GDestroyNotify notify)
3870 {
3871   GSource *source;
3872   guint id;
3873   
3874   g_return_val_if_fail (function != NULL, 0);
3875
3876   source = g_timeout_source_new (interval);
3877
3878   if (priority != G_PRIORITY_DEFAULT)
3879     g_source_set_priority (source, priority);
3880
3881   g_source_set_callback (source, function, data, notify);
3882   id = g_source_attach (source, NULL);
3883   g_source_unref (source);
3884
3885   return id;
3886 }
3887
3888 /**
3889  * g_timeout_add:
3890  * @interval: the time between calls to the function, in milliseconds
3891  *             (1/1000ths of a second)
3892  * @function: function to call
3893  * @data:     data to pass to @function
3894  * 
3895  * Sets a function to be called at regular intervals, with the default
3896  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3897  * until it returns %FALSE, at which point the timeout is automatically
3898  * destroyed and the function will not be called again.  The first call
3899  * to the function will be at the end of the first @interval.
3900  *
3901  * Note that timeout functions may be delayed, due to the processing of other
3902  * event sources. Thus they should not be relied on for precise timing.
3903  * After each call to the timeout function, the time of the next
3904  * timeout is recalculated based on the current time and the given interval
3905  * (it does not try to 'catch up' time lost in delays).
3906  *
3907  * If you want to have a timer in the "seconds" range and do not care
3908  * about the exact time of the first call of the timer, use the
3909  * g_timeout_add_seconds() function; this function allows for more
3910  * optimizations and more efficient system power usage.
3911  *
3912  * This internally creates a main loop source using g_timeout_source_new()
3913  * and attaches it to the main loop context using g_source_attach(). You can
3914  * do these steps manually if you need greater control.
3915  * 
3916  * The interval given is in terms of monotonic time, not wall clock
3917  * time.  See g_get_monotonic_time().
3918  * 
3919  * Return value: the ID (greater than 0) of the event source.
3920  **/
3921 guint
3922 g_timeout_add (guint32        interval,
3923                GSourceFunc    function,
3924                gpointer       data)
3925 {
3926   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3927                              interval, function, data, NULL);
3928 }
3929
3930 /**
3931  * g_timeout_add_seconds_full:
3932  * @priority: the priority of the timeout source. Typically this will be in
3933  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3934  * @interval: the time between calls to the function, in seconds
3935  * @function: function to call
3936  * @data:     data to pass to @function
3937  * @notify:   function to call when the timeout is removed, or %NULL
3938  *
3939  * Sets a function to be called at regular intervals, with @priority.
3940  * The function is called repeatedly until it returns %FALSE, at which
3941  * point the timeout is automatically destroyed and the function will
3942  * not be called again.
3943  *
3944  * Unlike g_timeout_add(), this function operates at whole second granularity.
3945  * The initial starting point of the timer is determined by the implementation
3946  * and the implementation is expected to group multiple timers together so that
3947  * they fire all at the same time.
3948  * To allow this grouping, the @interval to the first timer is rounded
3949  * and can deviate up to one second from the specified interval.
3950  * Subsequent timer iterations will generally run at the specified interval.
3951  *
3952  * Note that timeout functions may be delayed, due to the processing of other
3953  * event sources. Thus they should not be relied on for precise timing.
3954  * After each call to the timeout function, the time of the next
3955  * timeout is recalculated based on the current time and the given @interval
3956  *
3957  * If you want timing more precise than whole seconds, use g_timeout_add()
3958  * instead.
3959  *
3960  * The grouping of timers to fire at the same time results in a more power
3961  * and CPU efficient behavior so if your timer is in multiples of seconds
3962  * and you don't require the first timer exactly one second from now, the
3963  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3964  *
3965  * This internally creates a main loop source using 
3966  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3967  * using g_source_attach(). You can do these steps manually if you need 
3968  * greater control.
3969  * 
3970  * The interval given is in terms of monotonic time, not wall clock
3971  * time.  See g_get_monotonic_time().
3972  * 
3973  * Return value: the ID (greater than 0) of the event source.
3974  *
3975  * Rename to: g_timeout_add_seconds
3976  * Since: 2.14
3977  **/
3978 guint
3979 g_timeout_add_seconds_full (gint           priority,
3980                             guint32        interval,
3981                             GSourceFunc    function,
3982                             gpointer       data,
3983                             GDestroyNotify notify)
3984 {
3985   GSource *source;
3986   guint id;
3987
3988   g_return_val_if_fail (function != NULL, 0);
3989
3990   source = g_timeout_source_new_seconds (interval);
3991
3992   if (priority != G_PRIORITY_DEFAULT)
3993     g_source_set_priority (source, priority);
3994
3995   g_source_set_callback (source, function, data, notify);
3996   id = g_source_attach (source, NULL);
3997   g_source_unref (source);
3998
3999   return id;
4000 }
4001
4002 /**
4003  * g_timeout_add_seconds:
4004  * @interval: the time between calls to the function, in seconds
4005  * @function: function to call
4006  * @data: data to pass to @function
4007  *
4008  * Sets a function to be called at regular intervals with the default
4009  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4010  * it returns %FALSE, at which point the timeout is automatically destroyed
4011  * and the function will not be called again.
4012  *
4013  * This internally creates a main loop source using
4014  * g_timeout_source_new_seconds() and attaches it to the main loop context
4015  * using g_source_attach(). You can do these steps manually if you need
4016  * greater control. Also see g_timeout_add_seconds_full().
4017  *
4018  * Note that the first call of the timer may not be precise for timeouts
4019  * of one second. If you need finer precision and have such a timeout,
4020  * you may want to use g_timeout_add() instead.
4021  *
4022  * The interval given is in terms of monotonic time, not wall clock
4023  * time.  See g_get_monotonic_time().
4024  * 
4025  * Return value: the ID (greater than 0) of the event source.
4026  *
4027  * Since: 2.14
4028  **/
4029 guint
4030 g_timeout_add_seconds (guint       interval,
4031                        GSourceFunc function,
4032                        gpointer    data)
4033 {
4034   g_return_val_if_fail (function != NULL, 0);
4035
4036   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4037 }
4038
4039 /* Child watch functions */
4040
4041 #ifdef G_OS_WIN32
4042
4043 static gboolean
4044 g_child_watch_prepare (GSource *source,
4045                        gint    *timeout)
4046 {
4047   *timeout = -1;
4048   return FALSE;
4049 }
4050
4051 static gboolean 
4052 g_child_watch_check (GSource  *source)
4053 {
4054   GChildWatchSource *child_watch_source;
4055   gboolean child_exited;
4056
4057   child_watch_source = (GChildWatchSource *) source;
4058
4059   child_exited = child_watch_source->poll.revents & G_IO_IN;
4060
4061   if (child_exited)
4062     {
4063       DWORD child_status;
4064
4065       /*
4066        * Note: We do _not_ check for the special value of STILL_ACTIVE
4067        * since we know that the process has exited and doing so runs into
4068        * problems if the child process "happens to return STILL_ACTIVE(259)"
4069        * as Microsoft's Platform SDK puts it.
4070        */
4071       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4072         {
4073           gchar *emsg = g_win32_error_message (GetLastError ());
4074           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4075           g_free (emsg);
4076
4077           child_watch_source->child_status = -1;
4078         }
4079       else
4080         child_watch_source->child_status = child_status;
4081     }
4082
4083   return child_exited;
4084 }
4085
4086 static void
4087 g_child_watch_finalize (GSource *source)
4088 {
4089 }
4090
4091 #else /* G_OS_WIN32 */
4092
4093 static void
4094 wake_source (GSource *source)
4095 {
4096   GMainContext *context;
4097
4098   /* This should be thread-safe:
4099    *
4100    *  - if the source is currently being added to a context, that
4101    *    context will be woken up anyway
4102    *
4103    *  - if the source is currently being destroyed, we simply need not
4104    *    to crash:
4105    *
4106    *    - the memory for the source will remain valid until after the
4107    *      source finalize function was called (which would remove the
4108    *      source from the global list which we are currently holding the
4109    *      lock for)
4110    *
4111    *    - the GMainContext will either be NULL or point to a live
4112    *      GMainContext
4113    *
4114    *    - the GMainContext will remain valid since we hold the
4115    *      main_context_list lock
4116    *
4117    *  Since we are holding a lot of locks here, don't try to enter any
4118    *  more GMainContext functions for fear of dealock -- just hit the
4119    *  GWakeup and run.  Even if that's safe now, it could easily become
4120    *  unsafe with some very minor changes in the future, and signal
4121    *  handling is not the most well-tested codepath.
4122    */
4123   G_LOCK(main_context_list);
4124   context = source->context;
4125   if (context)
4126     g_wakeup_signal (context->wakeup);
4127   G_UNLOCK(main_context_list);
4128 }
4129
4130 static void
4131 dispatch_unix_signals (void)
4132 {
4133   GSList *node;
4134
4135   /* clear this first incase another one arrives while we're processing */
4136   any_unix_signal_pending = FALSE;
4137
4138   G_LOCK(unix_signal_lock);
4139
4140   /* handle GChildWatchSource instances */
4141   if (unix_signal_pending[SIGCHLD])
4142     {
4143       unix_signal_pending[SIGCHLD] = FALSE;
4144
4145       /* The only way we can do this is to scan all of the children.
4146        *
4147        * The docs promise that we will not reap children that we are not
4148        * explicitly watching, so that ties our hands from calling
4149        * waitpid(-1).  We also can't use siginfo's si_pid field since if
4150        * multiple SIGCHLD arrive at the same time, one of them can be
4151        * dropped (since a given UNIX signal can only be pending once).
4152        */
4153       for (node = unix_child_watches; node; node = node->next)
4154         {
4155           GChildWatchSource *source = node->data;
4156
4157           if (!source->child_exited)
4158             {
4159               if (waitpid (source->pid, &source->child_status, WNOHANG) > 0)
4160                 {
4161                   source->child_exited = TRUE;
4162
4163                   wake_source ((GSource *) source);
4164                 }
4165             }
4166         }
4167     }
4168
4169   /* handle GUnixSignalWatchSource instances */
4170   for (node = unix_signal_watches; node; node = node->next)
4171     {
4172       GUnixSignalWatchSource *source = node->data;
4173
4174       if (!source->pending)
4175         {
4176           if (unix_signal_pending[source->signum])
4177             {
4178               unix_signal_pending[source->signum] = FALSE;
4179               source->pending = TRUE;
4180
4181               wake_source ((GSource *) source);
4182             }
4183         }
4184     }
4185
4186   G_UNLOCK(unix_signal_lock);
4187 }
4188
4189 static gboolean
4190 g_child_watch_prepare (GSource *source,
4191                        gint    *timeout)
4192 {
4193   GChildWatchSource *child_watch_source;
4194
4195   child_watch_source = (GChildWatchSource *) source;
4196
4197   return child_watch_source->child_exited;
4198 }
4199
4200 static gboolean
4201 g_child_watch_check (GSource *source)
4202 {
4203   GChildWatchSource *child_watch_source;
4204
4205   child_watch_source = (GChildWatchSource *) source;
4206
4207   return child_watch_source->child_exited;
4208 }
4209
4210 static gboolean
4211 g_unix_signal_watch_prepare (GSource *source,
4212                              gint    *timeout)
4213 {
4214   GUnixSignalWatchSource *unix_signal_source;
4215
4216   unix_signal_source = (GUnixSignalWatchSource *) source;
4217
4218   return unix_signal_source->pending;
4219 }
4220
4221 static gboolean
4222 g_unix_signal_watch_check (GSource  *source)
4223 {
4224   GUnixSignalWatchSource *unix_signal_source;
4225
4226   unix_signal_source = (GUnixSignalWatchSource *) source;
4227
4228   return unix_signal_source->pending;
4229 }
4230
4231 static gboolean
4232 g_unix_signal_watch_dispatch (GSource    *source, 
4233                               GSourceFunc callback,
4234                               gpointer    user_data)
4235 {
4236   GUnixSignalWatchSource *unix_signal_source;
4237
4238   unix_signal_source = (GUnixSignalWatchSource *) source;
4239
4240   if (!callback)
4241     {
4242       g_warning ("Unix signal source dispatched without callback\n"
4243                  "You must call g_source_set_callback().");
4244       return FALSE;
4245     }
4246
4247   (callback) (user_data);
4248
4249   unix_signal_source->pending = FALSE;
4250
4251   return TRUE;
4252 }
4253
4254 static void
4255 ensure_unix_signal_handler_installed_unlocked (int signum)
4256 {
4257   static sigset_t installed_signal_mask;
4258   static gboolean initialized;
4259   struct sigaction action;
4260
4261   if (!initialized)
4262     {
4263       sigemptyset (&installed_signal_mask);
4264       g_get_worker_context ();
4265       initialized = TRUE;
4266     }
4267
4268   if (sigismember (&installed_signal_mask, signum))
4269     return;
4270
4271   sigaddset (&installed_signal_mask, signum);
4272
4273   action.sa_handler = g_unix_signal_handler;
4274   sigemptyset (&action.sa_mask);
4275   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4276   sigaction (signum, &action, NULL);
4277 }
4278
4279 GSource *
4280 _g_main_create_unix_signal_watch (int signum)
4281 {
4282   GSource *source;
4283   GUnixSignalWatchSource *unix_signal_source;
4284
4285   source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4286   unix_signal_source = (GUnixSignalWatchSource *) source;
4287
4288   unix_signal_source->signum = signum;
4289   unix_signal_source->pending = FALSE;
4290
4291   G_LOCK (unix_signal_lock);
4292   ensure_unix_signal_handler_installed_unlocked (signum);
4293   unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4294   if (unix_signal_pending[signum])
4295     unix_signal_source->pending = TRUE;
4296   unix_signal_pending[signum] = FALSE;
4297   G_UNLOCK (unix_signal_lock);
4298
4299   return source;
4300 }
4301
4302 static void
4303 g_unix_signal_watch_finalize (GSource    *source)
4304 {
4305   G_LOCK (unix_signal_lock);
4306   unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4307   G_UNLOCK (unix_signal_lock);
4308 }
4309
4310 static void
4311 g_child_watch_finalize (GSource *source)
4312 {
4313   G_LOCK (unix_signal_lock);
4314   unix_child_watches = g_slist_remove (unix_child_watches, source);
4315   G_UNLOCK (unix_signal_lock);
4316 }
4317
4318 #endif /* G_OS_WIN32 */
4319
4320 static gboolean
4321 g_child_watch_dispatch (GSource    *source, 
4322                         GSourceFunc callback,
4323                         gpointer    user_data)
4324 {
4325   GChildWatchSource *child_watch_source;
4326   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4327
4328   child_watch_source = (GChildWatchSource *) source;
4329
4330   if (!callback)
4331     {
4332       g_warning ("Child watch source dispatched without callback\n"
4333                  "You must call g_source_set_callback().");
4334       return FALSE;
4335     }
4336
4337   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4338
4339   /* We never keep a child watch source around as the child is gone */
4340   return FALSE;
4341 }
4342
4343 #ifndef G_OS_WIN32
4344
4345 static void
4346 g_unix_signal_handler (int signum)
4347 {
4348   unix_signal_pending[signum] = TRUE;
4349   any_unix_signal_pending = TRUE;
4350
4351   g_wakeup_signal (glib_worker_context->wakeup);
4352 }
4353
4354 #endif /* !G_OS_WIN32 */
4355
4356 /**
4357  * g_child_watch_source_new:
4358  * @pid: process to watch. On POSIX the pid of a child process. On
4359  * Windows a handle for a process (which doesn't have to be a child).
4360  * 
4361  * Creates a new child_watch source.
4362  *
4363  * The source will not initially be associated with any #GMainContext
4364  * and must be added to one with g_source_attach() before it will be
4365  * executed.
4366  * 
4367  * Note that child watch sources can only be used in conjunction with
4368  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4369  * flag is used.
4370  *
4371  * Note that on platforms where #GPid must be explicitly closed
4372  * (see g_spawn_close_pid()) @pid must not be closed while the
4373  * source is still active. Typically, you will want to call
4374  * g_spawn_close_pid() in the callback function for the source.
4375  *
4376  * Note further that using g_child_watch_source_new() is not 
4377  * compatible with calling <literal>waitpid(-1)</literal> in 
4378  * the application. Calling waitpid() for individual pids will
4379  * still work fine. 
4380  * 
4381  * Return value: the newly-created child watch source
4382  *
4383  * Since: 2.4
4384  **/
4385 GSource *
4386 g_child_watch_source_new (GPid pid)
4387 {
4388   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4389   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4390
4391   child_watch_source->pid = pid;
4392
4393 #ifdef G_OS_WIN32
4394   child_watch_source->poll.fd = (gintptr) pid;
4395   child_watch_source->poll.events = G_IO_IN;
4396
4397   g_source_add_poll (source, &child_watch_source->poll);
4398 #else /* G_OS_WIN32 */
4399   G_LOCK (unix_signal_lock);
4400   ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4401   unix_child_watches = g_slist_prepend (unix_child_watches, child_watch_source);
4402   if (waitpid (pid, &child_watch_source->child_status, WNOHANG) > 0)
4403     child_watch_source->child_exited = TRUE;
4404   G_UNLOCK (unix_signal_lock);
4405 #endif /* G_OS_WIN32 */
4406
4407   return source;
4408 }
4409
4410 /**
4411  * g_child_watch_add_full:
4412  * @priority: the priority of the idle source. Typically this will be in the
4413  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4414  * @pid:      process to watch. On POSIX the pid of a child process. On
4415  * Windows a handle for a process (which doesn't have to be a child).
4416  * @function: function to call
4417  * @data:     data to pass to @function
4418  * @notify:   function to call when the idle is removed, or %NULL
4419  * 
4420  * Sets a function to be called when the child indicated by @pid 
4421  * exits, at the priority @priority.
4422  *
4423  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4424  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4425  * the spawn function for the child watching to work.
4426  * 
4427  * Note that on platforms where #GPid must be explicitly closed
4428  * (see g_spawn_close_pid()) @pid must not be closed while the
4429  * source is still active. Typically, you will want to call
4430  * g_spawn_close_pid() in the callback function for the source.
4431  * 
4432  * GLib supports only a single callback per process id.
4433  *
4434  * This internally creates a main loop source using 
4435  * g_child_watch_source_new() and attaches it to the main loop context 
4436  * using g_source_attach(). You can do these steps manually if you 
4437  * need greater control.
4438  *
4439  * Return value: the ID (greater than 0) of the event source.
4440  *
4441  * Rename to: g_child_watch_add
4442  * Since: 2.4
4443  **/
4444 guint
4445 g_child_watch_add_full (gint            priority,
4446                         GPid            pid,
4447                         GChildWatchFunc function,
4448                         gpointer        data,
4449                         GDestroyNotify  notify)
4450 {
4451   GSource *source;
4452   guint id;
4453   
4454   g_return_val_if_fail (function != NULL, 0);
4455
4456   source = g_child_watch_source_new (pid);
4457
4458   if (priority != G_PRIORITY_DEFAULT)
4459     g_source_set_priority (source, priority);
4460
4461   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4462   id = g_source_attach (source, NULL);
4463   g_source_unref (source);
4464
4465   return id;
4466 }
4467
4468 /**
4469  * g_child_watch_add:
4470  * @pid:      process id to watch. On POSIX the pid of a child process. On
4471  * Windows a handle for a process (which doesn't have to be a child).
4472  * @function: function to call
4473  * @data:     data to pass to @function
4474  * 
4475  * Sets a function to be called when the child indicated by @pid 
4476  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4477  * 
4478  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4479  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4480  * the spawn function for the child watching to work.
4481  * 
4482  * Note that on platforms where #GPid must be explicitly closed
4483  * (see g_spawn_close_pid()) @pid must not be closed while the
4484  * source is still active. Typically, you will want to call
4485  * g_spawn_close_pid() in the callback function for the source.
4486  *
4487  * GLib supports only a single callback per process id.
4488  *
4489  * This internally creates a main loop source using 
4490  * g_child_watch_source_new() and attaches it to the main loop context 
4491  * using g_source_attach(). You can do these steps manually if you 
4492  * need greater control.
4493  *
4494  * Return value: the ID (greater than 0) of the event source.
4495  *
4496  * Since: 2.4
4497  **/
4498 guint 
4499 g_child_watch_add (GPid            pid,
4500                    GChildWatchFunc function,
4501                    gpointer        data)
4502 {
4503   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4504 }
4505
4506
4507 /* Idle functions */
4508
4509 static gboolean 
4510 g_idle_prepare  (GSource  *source,
4511                  gint     *timeout)
4512 {
4513   *timeout = 0;
4514
4515   return TRUE;
4516 }
4517
4518 static gboolean 
4519 g_idle_check    (GSource  *source)
4520 {
4521   return TRUE;
4522 }
4523
4524 static gboolean
4525 g_idle_dispatch (GSource    *source, 
4526                  GSourceFunc callback,
4527                  gpointer    user_data)
4528 {
4529   if (!callback)
4530     {
4531       g_warning ("Idle source dispatched without callback\n"
4532                  "You must call g_source_set_callback().");
4533       return FALSE;
4534     }
4535   
4536   return callback (user_data);
4537 }
4538
4539 /**
4540  * g_idle_source_new:
4541  * 
4542  * Creates a new idle source.
4543  *
4544  * The source will not initially be associated with any #GMainContext
4545  * and must be added to one with g_source_attach() before it will be
4546  * executed. Note that the default priority for idle sources is
4547  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4548  * have a default priority of %G_PRIORITY_DEFAULT.
4549  * 
4550  * Return value: the newly-created idle source
4551  **/
4552 GSource *
4553 g_idle_source_new (void)
4554 {
4555   GSource *source;
4556
4557   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4558   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4559
4560   return source;
4561 }
4562
4563 /**
4564  * g_idle_add_full:
4565  * @priority: the priority of the idle source. Typically this will be in the
4566  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4567  * @function: function to call
4568  * @data:     data to pass to @function
4569  * @notify:   function to call when the idle is removed, or %NULL
4570  * 
4571  * Adds a function to be called whenever there are no higher priority
4572  * events pending.  If the function returns %FALSE it is automatically
4573  * removed from the list of event sources and will not be called again.
4574  * 
4575  * This internally creates a main loop source using g_idle_source_new()
4576  * and attaches it to the main loop context using g_source_attach(). 
4577  * You can do these steps manually if you need greater control.
4578  * 
4579  * Return value: the ID (greater than 0) of the event source.
4580  * Rename to: g_idle_add
4581  **/
4582 guint 
4583 g_idle_add_full (gint           priority,
4584                  GSourceFunc    function,
4585                  gpointer       data,
4586                  GDestroyNotify notify)
4587 {
4588   GSource *source;
4589   guint id;
4590   
4591   g_return_val_if_fail (function != NULL, 0);
4592
4593   source = g_idle_source_new ();
4594
4595   if (priority != G_PRIORITY_DEFAULT_IDLE)
4596     g_source_set_priority (source, priority);
4597
4598   g_source_set_callback (source, function, data, notify);
4599   id = g_source_attach (source, NULL);
4600   g_source_unref (source);
4601
4602   return id;
4603 }
4604
4605 /**
4606  * g_idle_add:
4607  * @function: function to call 
4608  * @data: data to pass to @function.
4609  * 
4610  * Adds a function to be called whenever there are no higher priority
4611  * events pending to the default main loop. The function is given the
4612  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4613  * returns %FALSE it is automatically removed from the list of event
4614  * sources and will not be called again.
4615  * 
4616  * This internally creates a main loop source using g_idle_source_new()
4617  * and attaches it to the main loop context using g_source_attach(). 
4618  * You can do these steps manually if you need greater control.
4619  * 
4620  * Return value: the ID (greater than 0) of the event source.
4621  **/
4622 guint 
4623 g_idle_add (GSourceFunc    function,
4624             gpointer       data)
4625 {
4626   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4627 }
4628
4629 /**
4630  * g_idle_remove_by_data:
4631  * @data: the data for the idle source's callback.
4632  * 
4633  * Removes the idle function with the given data.
4634  * 
4635  * Return value: %TRUE if an idle source was found and removed.
4636  **/
4637 gboolean
4638 g_idle_remove_by_data (gpointer data)
4639 {
4640   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4641 }
4642
4643 /**
4644  * g_main_context_invoke:
4645  * @context: (allow-none): a #GMainContext, or %NULL
4646  * @function: function to call
4647  * @data: data to pass to @function
4648  *
4649  * Invokes a function in such a way that @context is owned during the
4650  * invocation of @function.
4651  *
4652  * If @context is %NULL then the global default main context — as
4653  * returned by g_main_context_default() — is used.
4654  *
4655  * If @context is owned by the current thread, @function is called
4656  * directly.  Otherwise, if @context is the thread-default main context
4657  * of the current thread and g_main_context_acquire() succeeds, then
4658  * @function is called and g_main_context_release() is called
4659  * afterwards.
4660  *
4661  * In any other case, an idle source is created to call @function and
4662  * that source is attached to @context (presumably to be run in another
4663  * thread).  The idle source is attached with #G_PRIORITY_DEFAULT
4664  * priority.  If you want a different priority, use
4665  * g_main_context_invoke_full().
4666  *
4667  * Note that, as with normal idle functions, @function should probably
4668  * return %FALSE.  If it returns %TRUE, it will be continuously run in a
4669  * loop (and may prevent this call from returning).
4670  *
4671  * Since: 2.28
4672  **/
4673 void
4674 g_main_context_invoke (GMainContext *context,
4675                        GSourceFunc   function,
4676                        gpointer      data)
4677 {
4678   g_main_context_invoke_full (context,
4679                               G_PRIORITY_DEFAULT,
4680                               function, data, NULL);
4681 }
4682
4683 /**
4684  * g_main_context_invoke_full:
4685  * @context: (allow-none): a #GMainContext, or %NULL
4686  * @priority: the priority at which to run @function
4687  * @function: function to call
4688  * @data: data to pass to @function
4689  * @notify: a function to call when @data is no longer in use, or %NULL.
4690  *
4691  * Invokes a function in such a way that @context is owned during the
4692  * invocation of @function.
4693  *
4694  * This function is the same as g_main_context_invoke() except that it
4695  * lets you specify the priority incase @function ends up being
4696  * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4697  *
4698  * @notify should not assume that it is called from any particular
4699  * thread or with any particular context acquired.
4700  *
4701  * Since: 2.28
4702  **/
4703 void
4704 g_main_context_invoke_full (GMainContext   *context,
4705                             gint            priority,
4706                             GSourceFunc     function,
4707                             gpointer        data,
4708                             GDestroyNotify  notify)
4709 {
4710   g_return_if_fail (function != NULL);
4711
4712   if (!context)
4713     context = g_main_context_default ();
4714
4715   if (g_main_context_is_owner (context))
4716     {
4717       while (function (data));
4718       if (notify != NULL)
4719         notify (data);
4720     }
4721
4722   else
4723     {
4724       GMainContext *thread_default;
4725
4726       thread_default = g_main_context_get_thread_default ();
4727
4728       if (!thread_default)
4729         thread_default = g_main_context_default ();
4730
4731       if (thread_default == context && g_main_context_acquire (context))
4732         {
4733           while (function (data));
4734
4735           g_main_context_release (context);
4736
4737           if (notify != NULL)
4738             notify (data);
4739         }
4740       else
4741         {
4742           GSource *source;
4743
4744           source = g_idle_source_new ();
4745           g_source_set_priority (source, priority);
4746           g_source_set_callback (source, function, data, notify);
4747           g_source_attach (source, context);
4748           g_source_unref (source);
4749         }
4750     }
4751 }
4752
4753 static gpointer
4754 glib_worker_main (gpointer data)
4755 {
4756   while (TRUE)
4757     {
4758       g_main_context_iteration (glib_worker_context, TRUE);
4759
4760 #ifdef G_OS_UNIX
4761       if (any_unix_signal_pending)
4762         dispatch_unix_signals ();
4763 #endif
4764     }
4765
4766   return NULL; /* worst GCC warning message ever... */
4767 }
4768
4769 GMainContext *
4770 g_get_worker_context (void)
4771 {
4772   static gsize initialised;
4773
4774   if (g_once_init_enter (&initialised))
4775     {
4776       GError *error = NULL;
4777
4778       glib_worker_context = g_main_context_new ();
4779       if (g_thread_new ("gmain", glib_worker_main, NULL, FALSE, &error) == NULL)
4780         g_error ("Creating GLib worker thread failed: %s\n", error->message);
4781
4782       g_once_init_leave (&initialised, TRUE);
4783     }
4784
4785   return glib_worker_context;
4786 }