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