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