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