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