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