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