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