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