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