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