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