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