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