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