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