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