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