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