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_slist_free (source->poll_fds);
1420       source->poll_fds = NULL;
1421       g_free (source);
1422     }
1423   
1424   if (!have_lock && context)
1425     UNLOCK_CONTEXT (context);
1426
1427   if (old_cb_funcs)
1428     {
1429       if (have_lock)
1430         UNLOCK_CONTEXT (context);
1431       
1432       old_cb_funcs->unref (old_cb_data);
1433
1434       if (have_lock)
1435         LOCK_CONTEXT (context);
1436     }
1437 }
1438
1439 /**
1440  * g_source_unref:
1441  * @source: a #GSource
1442  * 
1443  * Decreases the reference count of a source by one. If the
1444  * resulting reference count is zero the source and associated
1445  * memory will be destroyed. 
1446  **/
1447 void
1448 g_source_unref (GSource *source)
1449 {
1450   g_return_if_fail (source != NULL);
1451
1452   g_source_unref_internal (source, source->context, FALSE);
1453 }
1454
1455 /**
1456  * g_main_context_find_source_by_id:
1457  * @context: a #GMainContext (if %NULL, the default context will be used)
1458  * @source_id: the source ID, as returned by g_source_get_id(). 
1459  * 
1460  * Finds a #GSource given a pair of context and ID.
1461  * 
1462  * Return value: the #GSource if found, otherwise, %NULL
1463  **/
1464 GSource *
1465 g_main_context_find_source_by_id (GMainContext *context,
1466                                   guint         source_id)
1467 {
1468   GSource *source;
1469   
1470   g_return_val_if_fail (source_id > 0, NULL);
1471
1472   if (context == NULL)
1473     context = g_main_context_default ();
1474   
1475   LOCK_CONTEXT (context);
1476   
1477   source = context->source_list;
1478   while (source)
1479     {
1480       if (!SOURCE_DESTROYED (source) &&
1481           source->source_id == source_id)
1482         break;
1483       source = source->next;
1484     }
1485
1486   UNLOCK_CONTEXT (context);
1487
1488   return source;
1489 }
1490
1491 /**
1492  * g_main_context_find_source_by_funcs_user_data:
1493  * @context: a #GMainContext (if %NULL, the default context will be used).
1494  * @funcs: the @source_funcs passed to g_source_new().
1495  * @user_data: the user data from the callback.
1496  * 
1497  * Finds a source with the given source functions and user data.  If
1498  * multiple sources exist with the same source function and user data,
1499  * the first one found will be returned.
1500  * 
1501  * Return value: the source, if one was found, otherwise %NULL
1502  **/
1503 GSource *
1504 g_main_context_find_source_by_funcs_user_data (GMainContext *context,
1505                                                GSourceFuncs *funcs,
1506                                                gpointer      user_data)
1507 {
1508   GSource *source;
1509   
1510   g_return_val_if_fail (funcs != NULL, NULL);
1511
1512   if (context == NULL)
1513     context = g_main_context_default ();
1514   
1515   LOCK_CONTEXT (context);
1516
1517   source = context->source_list;
1518   while (source)
1519     {
1520       if (!SOURCE_DESTROYED (source) &&
1521           source->source_funcs == funcs &&
1522           source->callback_funcs)
1523         {
1524           GSourceFunc callback;
1525           gpointer callback_data;
1526
1527           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1528           
1529           if (callback_data == user_data)
1530             break;
1531         }
1532       source = source->next;
1533     }
1534
1535   UNLOCK_CONTEXT (context);
1536
1537   return source;
1538 }
1539
1540 /**
1541  * g_main_context_find_source_by_user_data:
1542  * @context: a #GMainContext
1543  * @user_data: the user_data for the callback.
1544  * 
1545  * Finds a source with the given user data for the callback.  If
1546  * multiple sources exist with the same user data, the first
1547  * one found will be returned.
1548  * 
1549  * Return value: the source, if one was found, otherwise %NULL
1550  **/
1551 GSource *
1552 g_main_context_find_source_by_user_data (GMainContext *context,
1553                                          gpointer      user_data)
1554 {
1555   GSource *source;
1556   
1557   if (context == NULL)
1558     context = g_main_context_default ();
1559   
1560   LOCK_CONTEXT (context);
1561
1562   source = context->source_list;
1563   while (source)
1564     {
1565       if (!SOURCE_DESTROYED (source) &&
1566           source->callback_funcs)
1567         {
1568           GSourceFunc callback;
1569           gpointer callback_data = NULL;
1570
1571           source->callback_funcs->get (source->callback_data, source, &callback, &callback_data);
1572
1573           if (callback_data == user_data)
1574             break;
1575         }
1576       source = source->next;
1577     }
1578
1579   UNLOCK_CONTEXT (context);
1580
1581   return source;
1582 }
1583
1584 /**
1585  * g_source_remove:
1586  * @tag: the ID of the source to remove.
1587  * 
1588  * Removes the source with the given id from the default main context. 
1589  * The id of
1590  * a #GSource is given by g_source_get_id(), or will be returned by the
1591  * functions g_source_attach(), g_idle_add(), g_idle_add_full(),
1592  * g_timeout_add(), g_timeout_add_full(), g_child_watch_add(),
1593  * g_child_watch_add_full(), g_io_add_watch(), and g_io_add_watch_full().
1594  *
1595  * See also g_source_destroy(). You must use g_source_destroy() for sources
1596  * added to a non-default main context.
1597  *
1598  * Return value: %TRUE if the source was found and removed.
1599  **/
1600 gboolean
1601 g_source_remove (guint tag)
1602 {
1603   GSource *source;
1604   
1605   g_return_val_if_fail (tag > 0, FALSE);
1606
1607   source = g_main_context_find_source_by_id (NULL, tag);
1608   if (source)
1609     g_source_destroy (source);
1610
1611   return source != NULL;
1612 }
1613
1614 /**
1615  * g_source_remove_by_user_data:
1616  * @user_data: the user_data for the callback.
1617  * 
1618  * Removes a source from the default main loop context given the user
1619  * data for the callback. If multiple sources exist with the same user
1620  * data, only one will be destroyed.
1621  * 
1622  * Return value: %TRUE if a source was found and removed. 
1623  **/
1624 gboolean
1625 g_source_remove_by_user_data (gpointer user_data)
1626 {
1627   GSource *source;
1628   
1629   source = g_main_context_find_source_by_user_data (NULL, user_data);
1630   if (source)
1631     {
1632       g_source_destroy (source);
1633       return TRUE;
1634     }
1635   else
1636     return FALSE;
1637 }
1638
1639 /**
1640  * g_source_remove_by_funcs_user_data:
1641  * @funcs: The @source_funcs passed to g_source_new()
1642  * @user_data: the user data for the callback
1643  * 
1644  * Removes a source from the default main loop context given the
1645  * source functions and user data. If multiple sources exist with the
1646  * same source functions and user data, only one will be destroyed.
1647  * 
1648  * Return value: %TRUE if a source was found and removed. 
1649  **/
1650 gboolean
1651 g_source_remove_by_funcs_user_data (GSourceFuncs *funcs,
1652                                     gpointer      user_data)
1653 {
1654   GSource *source;
1655
1656   g_return_val_if_fail (funcs != NULL, FALSE);
1657
1658   source = g_main_context_find_source_by_funcs_user_data (NULL, funcs, user_data);
1659   if (source)
1660     {
1661       g_source_destroy (source);
1662       return TRUE;
1663     }
1664   else
1665     return FALSE;
1666 }
1667
1668 /**
1669  * g_get_current_time:
1670  * @result: #GTimeVal structure in which to store current time.
1671  * 
1672  * Equivalent to the UNIX gettimeofday() function, but portable.
1673  **/
1674 void
1675 g_get_current_time (GTimeVal *result)
1676 {
1677 #ifndef G_OS_WIN32
1678   struct timeval r;
1679
1680   g_return_if_fail (result != NULL);
1681
1682   /*this is required on alpha, there the timeval structs are int's
1683     not longs and a cast only would fail horribly*/
1684   gettimeofday (&r, NULL);
1685   result->tv_sec = r.tv_sec;
1686   result->tv_usec = r.tv_usec;
1687 #else
1688   FILETIME ft;
1689   guint64 time64;
1690
1691   g_return_if_fail (result != NULL);
1692
1693   GetSystemTimeAsFileTime (&ft);
1694   memmove (&time64, &ft, sizeof (FILETIME));
1695
1696   /* Convert from 100s of nanoseconds since 1601-01-01
1697    * to Unix epoch. Yes, this is Y2038 unsafe.
1698    */
1699   time64 -= G_GINT64_CONSTANT (116444736000000000);
1700   time64 /= 10;
1701
1702   result->tv_sec = time64 / 1000000;
1703   result->tv_usec = time64 % 1000000;
1704 #endif
1705 }
1706
1707 static void
1708 g_main_dispatch_free (gpointer dispatch)
1709 {
1710   g_slice_free (GMainDispatch, dispatch);
1711 }
1712
1713 /* Running the main loop */
1714
1715 static GMainDispatch *
1716 get_dispatch (void)
1717 {
1718   static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
1719   GMainDispatch *dispatch = g_static_private_get (&depth_private);
1720   if (!dispatch)
1721     {
1722       dispatch = g_slice_new0 (GMainDispatch);
1723       g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
1724     }
1725
1726   return dispatch;
1727 }
1728
1729 /**
1730  * g_main_depth:
1731  *
1732  * Returns the depth of the stack of calls to
1733  * g_main_context_dispatch() on any #GMainContext in the current thread.
1734  *  That is, when called from the toplevel, it gives 0. When
1735  * called from within a callback from g_main_context_iteration()
1736  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
1737  * a callback to a recursive call to g_main_context_iterate(),
1738  * it returns 2. And so forth.
1739  *
1740  * This function is useful in a situation like the following:
1741  * Imagine an extremely simple "garbage collected" system.
1742  *
1743  * |[
1744  * static GList *free_list;
1745  * 
1746  * gpointer
1747  * allocate_memory (gsize size)
1748  * { 
1749  *   gpointer result = g_malloc (size);
1750  *   free_list = g_list_prepend (free_list, result);
1751  *   return result;
1752  * }
1753  * 
1754  * void
1755  * free_allocated_memory (void)
1756  * {
1757  *   GList *l;
1758  *   for (l = free_list; l; l = l->next);
1759  *     g_free (l->data);
1760  *   g_list_free (free_list);
1761  *   free_list = NULL;
1762  *  }
1763  * 
1764  * [...]
1765  * 
1766  * while (TRUE); 
1767  *  {
1768  *    g_main_context_iteration (NULL, TRUE);
1769  *    free_allocated_memory();
1770  *   }
1771  * ]|
1772  *
1773  * This works from an application, however, if you want to do the same
1774  * thing from a library, it gets more difficult, since you no longer
1775  * control the main loop. You might think you can simply use an idle
1776  * function to make the call to free_allocated_memory(), but that
1777  * doesn't work, since the idle function could be called from a
1778  * recursive callback. This can be fixed by using g_main_depth()
1779  *
1780  * |[
1781  * gpointer
1782  * allocate_memory (gsize size)
1783  * { 
1784  *   FreeListBlock *block = g_new (FreeListBlock, 1);
1785  *   block->mem = g_malloc (size);
1786  *   block->depth = g_main_depth ();   
1787  *   free_list = g_list_prepend (free_list, block);
1788  *   return block->mem;
1789  * }
1790  * 
1791  * void
1792  * free_allocated_memory (void)
1793  * {
1794  *   GList *l;
1795  *   
1796  *   int depth = g_main_depth ();
1797  *   for (l = free_list; l; );
1798  *     {
1799  *       GList *next = l->next;
1800  *       FreeListBlock *block = l->data;
1801  *       if (block->depth > depth)
1802  *         {
1803  *           g_free (block->mem);
1804  *           g_free (block);
1805  *           free_list = g_list_delete_link (free_list, l);
1806  *         }
1807  *               
1808  *       l = next;
1809  *     }
1810  *   }
1811  * ]|
1812  *
1813  * There is a temptation to use g_main_depth() to solve
1814  * problems with reentrancy. For instance, while waiting for data
1815  * to be received from the network in response to a menu item,
1816  * the menu item might be selected again. It might seem that
1817  * one could make the menu item's callback return immediately
1818  * and do nothing if g_main_depth() returns a value greater than 1.
1819  * However, this should be avoided since the user then sees selecting
1820  * the menu item do nothing. Furthermore, you'll find yourself adding
1821  * these checks all over your code, since there are doubtless many,
1822  * many things that the user could do. Instead, you can use the
1823  * following techniques:
1824  *
1825  * <orderedlist>
1826  *  <listitem>
1827  *   <para>
1828  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
1829  *     the user from interacting with elements while the main
1830  *     loop is recursing.
1831  *   </para>
1832  *  </listitem>
1833  *  <listitem>
1834  *   <para>
1835  *     Avoid main loop recursion in situations where you can't handle
1836  *     arbitrary  callbacks. Instead, structure your code so that you
1837  *     simply return to the main loop and then get called again when
1838  *     there is more work to do.
1839  *   </para>
1840  *  </listitem>
1841  * </orderedlist>
1842  * 
1843  * Return value: The main loop recursion level in the current thread
1844  **/
1845 int
1846 g_main_depth (void)
1847 {
1848   GMainDispatch *dispatch = get_dispatch ();
1849   return dispatch->depth;
1850 }
1851
1852 /**
1853  * g_main_current_source:
1854  *
1855  * Returns the currently firing source for this thread.
1856  * 
1857  * Return value: The currently firing source or %NULL.
1858  *
1859  * Since: 2.12
1860  */
1861 GSource *
1862 g_main_current_source (void)
1863 {
1864   GMainDispatch *dispatch = get_dispatch ();
1865   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
1866 }
1867
1868 /**
1869  * g_source_is_destroyed:
1870  * @source: a #GSource
1871  *
1872  * Returns whether @source has been destroyed.
1873  *
1874  * This is important when you operate upon your objects 
1875  * from within idle handlers, but may have freed the object 
1876  * before the dispatch of your idle handler.
1877  *
1878  * |[
1879  * static gboolean 
1880  * idle_callback (gpointer data)
1881  * {
1882  *   SomeWidget *self = data;
1883  *    
1884  *   GDK_THREADS_ENTER (<!-- -->);
1885  *   /<!-- -->* do stuff with self *<!-- -->/
1886  *   self->idle_id = 0;
1887  *   GDK_THREADS_LEAVE (<!-- -->);
1888  *    
1889  *   return FALSE;
1890  * }
1891  *  
1892  * static void 
1893  * some_widget_do_stuff_later (SomeWidget *self)
1894  * {
1895  *   self->idle_id = g_idle_add (idle_callback, self);
1896  * }
1897  *  
1898  * static void 
1899  * some_widget_finalize (GObject *object)
1900  * {
1901  *   SomeWidget *self = SOME_WIDGET (object);
1902  *    
1903  *   if (self->idle_id)
1904  *     g_source_remove (self->idle_id);
1905  *    
1906  *   G_OBJECT_CLASS (parent_class)->finalize (object);
1907  * }
1908  * ]|
1909  *
1910  * This will fail in a multi-threaded application if the 
1911  * widget is destroyed before the idle handler fires due 
1912  * to the use after free in the callback. A solution, to 
1913  * this particular problem, is to check to if the source
1914  * has already been destroy within the callback.
1915  *
1916  * |[
1917  * static gboolean 
1918  * idle_callback (gpointer data)
1919  * {
1920  *   SomeWidget *self = data;
1921  *   
1922  *   GDK_THREADS_ENTER ();
1923  *   if (!g_source_is_destroyed (g_main_current_source ()))
1924  *     {
1925  *       /<!-- -->* do stuff with self *<!-- -->/
1926  *     }
1927  *   GDK_THREADS_LEAVE ();
1928  *   
1929  *   return FALSE;
1930  * }
1931  * ]|
1932  *
1933  * Return value: %TRUE if the source has been destroyed
1934  *
1935  * Since: 2.12
1936  */
1937 gboolean
1938 g_source_is_destroyed (GSource *source)
1939 {
1940   return SOURCE_DESTROYED (source);
1941 }
1942
1943 /* Temporarily remove all this source's file descriptors from the
1944  * poll(), so that if data comes available for one of the file descriptors
1945  * we don't continually spin in the poll()
1946  */
1947 /* HOLDS: source->context's lock */
1948 static void
1949 block_source (GSource *source)
1950 {
1951   GSList *tmp_list;
1952
1953   g_return_if_fail (!SOURCE_BLOCKED (source));
1954
1955   tmp_list = source->poll_fds;
1956   while (tmp_list)
1957     {
1958       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
1959       tmp_list = tmp_list->next;
1960     }
1961 }
1962
1963 /* HOLDS: source->context's lock */
1964 static void
1965 unblock_source (GSource *source)
1966 {
1967   GSList *tmp_list;
1968   
1969   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
1970   g_return_if_fail (!SOURCE_DESTROYED (source));
1971   
1972   tmp_list = source->poll_fds;
1973   while (tmp_list)
1974     {
1975       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
1976       tmp_list = tmp_list->next;
1977     }
1978 }
1979
1980 /* HOLDS: context's lock */
1981 static void
1982 g_main_dispatch (GMainContext *context)
1983 {
1984   GMainDispatch *current = get_dispatch ();
1985   guint i;
1986
1987   for (i = 0; i < context->pending_dispatches->len; i++)
1988     {
1989       GSource *source = context->pending_dispatches->pdata[i];
1990
1991       context->pending_dispatches->pdata[i] = NULL;
1992       g_assert (source);
1993
1994       source->flags &= ~G_SOURCE_READY;
1995
1996       if (!SOURCE_DESTROYED (source))
1997         {
1998           gboolean was_in_call;
1999           gpointer user_data = NULL;
2000           GSourceFunc callback = NULL;
2001           GSourceCallbackFuncs *cb_funcs;
2002           gpointer cb_data;
2003           gboolean need_destroy;
2004
2005           gboolean (*dispatch) (GSource *,
2006                                 GSourceFunc,
2007                                 gpointer);
2008           GSList current_source_link;
2009
2010           dispatch = source->source_funcs->dispatch;
2011           cb_funcs = source->callback_funcs;
2012           cb_data = source->callback_data;
2013
2014           if (cb_funcs)
2015             cb_funcs->ref (cb_data);
2016           
2017           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2018             block_source (source);
2019           
2020           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2021           source->flags |= G_HOOK_FLAG_IN_CALL;
2022
2023           if (cb_funcs)
2024             cb_funcs->get (cb_data, source, &callback, &user_data);
2025
2026           UNLOCK_CONTEXT (context);
2027
2028           current->depth++;
2029           /* The on-stack allocation of the GSList is unconventional, but
2030            * we know that the lifetime of the link is bounded to this
2031            * function as the link is kept in a thread specific list and
2032            * not manipulated outside of this function and its descendants.
2033            * Avoiding the overhead of a g_slist_alloc() is useful as many
2034            * applications do little more than dispatch events.
2035            *
2036            * This is a performance hack - do not revert to g_slist_prepend()!
2037            */
2038           current_source_link.data = source;
2039           current_source_link.next = current->dispatching_sources;
2040           current->dispatching_sources = &current_source_link;
2041           need_destroy = ! dispatch (source,
2042                                      callback,
2043                                      user_data);
2044           g_assert (current->dispatching_sources == &current_source_link);
2045           current->dispatching_sources = current_source_link.next;
2046           current->depth--;
2047           
2048           if (cb_funcs)
2049             cb_funcs->unref (cb_data);
2050
2051           LOCK_CONTEXT (context);
2052           
2053           if (!was_in_call)
2054             source->flags &= ~G_HOOK_FLAG_IN_CALL;
2055
2056           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2057               !SOURCE_DESTROYED (source))
2058             unblock_source (source);
2059           
2060           /* Note: this depends on the fact that we can't switch
2061            * sources from one main context to another
2062            */
2063           if (need_destroy && !SOURCE_DESTROYED (source))
2064             {
2065               g_assert (source->context == context);
2066               g_source_destroy_internal (source, context, TRUE);
2067             }
2068         }
2069       
2070       SOURCE_UNREF (source, context);
2071     }
2072
2073   g_ptr_array_set_size (context->pending_dispatches, 0);
2074 }
2075
2076 /* Holds context's lock */
2077 static inline GSource *
2078 next_valid_source (GMainContext *context,
2079                    GSource      *source)
2080 {
2081   GSource *new_source = source ? source->next : context->source_list;
2082
2083   while (new_source)
2084     {
2085       if (!SOURCE_DESTROYED (new_source))
2086         {
2087           new_source->ref_count++;
2088           break;
2089         }
2090       
2091       new_source = new_source->next;
2092     }
2093
2094   if (source)
2095     SOURCE_UNREF (source, context);
2096           
2097   return new_source;
2098 }
2099
2100 /**
2101  * g_main_context_acquire:
2102  * @context: a #GMainContext
2103  * 
2104  * Tries to become the owner of the specified context.
2105  * If some other thread is the owner of the context,
2106  * returns %FALSE immediately. Ownership is properly
2107  * recursive: the owner can require ownership again
2108  * and will release ownership when g_main_context_release()
2109  * is called as many times as g_main_context_acquire().
2110  *
2111  * You must be the owner of a context before you
2112  * can call g_main_context_prepare(), g_main_context_query(),
2113  * g_main_context_check(), g_main_context_dispatch().
2114  * 
2115  * Return value: %TRUE if the operation succeeded, and
2116  *   this thread is now the owner of @context.
2117  **/
2118 gboolean 
2119 g_main_context_acquire (GMainContext *context)
2120 {
2121 #ifdef G_THREADS_ENABLED
2122   gboolean result = FALSE;
2123   GThread *self = G_THREAD_SELF;
2124
2125   if (context == NULL)
2126     context = g_main_context_default ();
2127   
2128   LOCK_CONTEXT (context);
2129
2130   if (!context->owner)
2131     {
2132       context->owner = self;
2133       g_assert (context->owner_count == 0);
2134     }
2135
2136   if (context->owner == self)
2137     {
2138       context->owner_count++;
2139       result = TRUE;
2140     }
2141
2142   UNLOCK_CONTEXT (context); 
2143   
2144   return result;
2145 #else /* !G_THREADS_ENABLED */
2146   return TRUE;
2147 #endif /* G_THREADS_ENABLED */
2148 }
2149
2150 /**
2151  * g_main_context_release:
2152  * @context: a #GMainContext
2153  * 
2154  * Releases ownership of a context previously acquired by this thread
2155  * with g_main_context_acquire(). If the context was acquired multiple
2156  * times, the ownership will be released only when g_main_context_release()
2157  * is called as many times as it was acquired.
2158  **/
2159 void
2160 g_main_context_release (GMainContext *context)
2161 {
2162 #ifdef G_THREADS_ENABLED
2163   if (context == NULL)
2164     context = g_main_context_default ();
2165   
2166   LOCK_CONTEXT (context);
2167
2168   context->owner_count--;
2169   if (context->owner_count == 0)
2170     {
2171       context->owner = NULL;
2172
2173       if (context->waiters)
2174         {
2175           GMainWaiter *waiter = context->waiters->data;
2176           gboolean loop_internal_waiter =
2177             (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2178           context->waiters = g_slist_delete_link (context->waiters,
2179                                                   context->waiters);
2180           if (!loop_internal_waiter)
2181             g_mutex_lock (waiter->mutex);
2182           
2183           g_cond_signal (waiter->cond);
2184           
2185           if (!loop_internal_waiter)
2186             g_mutex_unlock (waiter->mutex);
2187         }
2188     }
2189
2190   UNLOCK_CONTEXT (context); 
2191 #endif /* G_THREADS_ENABLED */
2192 }
2193
2194 /**
2195  * g_main_context_wait:
2196  * @context: a #GMainContext
2197  * @cond: a condition variable
2198  * @mutex: a mutex, currently held
2199  * 
2200  * Tries to become the owner of the specified context,
2201  * as with g_main_context_acquire(). But if another thread
2202  * is the owner, atomically drop @mutex and wait on @cond until 
2203  * that owner releases ownership or until @cond is signaled, then
2204  * try again (once) to become the owner.
2205  * 
2206  * Return value: %TRUE if the operation succeeded, and
2207  *   this thread is now the owner of @context.
2208  **/
2209 gboolean
2210 g_main_context_wait (GMainContext *context,
2211                      GCond        *cond,
2212                      GMutex       *mutex)
2213 {
2214 #ifdef G_THREADS_ENABLED
2215   gboolean result = FALSE;
2216   GThread *self = G_THREAD_SELF;
2217   gboolean loop_internal_waiter;
2218   
2219   if (context == NULL)
2220     context = g_main_context_default ();
2221
2222   loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2223   
2224   if (!loop_internal_waiter)
2225     LOCK_CONTEXT (context);
2226
2227   if (context->owner && context->owner != self)
2228     {
2229       GMainWaiter waiter;
2230
2231       waiter.cond = cond;
2232       waiter.mutex = mutex;
2233
2234       context->waiters = g_slist_append (context->waiters, &waiter);
2235       
2236       if (!loop_internal_waiter)
2237         UNLOCK_CONTEXT (context);
2238       g_cond_wait (cond, mutex);
2239       if (!loop_internal_waiter)      
2240         LOCK_CONTEXT (context);
2241
2242       context->waiters = g_slist_remove (context->waiters, &waiter);
2243     }
2244
2245   if (!context->owner)
2246     {
2247       context->owner = self;
2248       g_assert (context->owner_count == 0);
2249     }
2250
2251   if (context->owner == self)
2252     {
2253       context->owner_count++;
2254       result = TRUE;
2255     }
2256
2257   if (!loop_internal_waiter)
2258     UNLOCK_CONTEXT (context); 
2259   
2260   return result;
2261 #else /* !G_THREADS_ENABLED */
2262   return TRUE;
2263 #endif /* G_THREADS_ENABLED */
2264 }
2265
2266 /**
2267  * g_main_context_prepare:
2268  * @context: a #GMainContext
2269  * @priority: location to store priority of highest priority
2270  *            source already ready.
2271  * 
2272  * Prepares to poll sources within a main loop. The resulting information
2273  * for polling is determined by calling g_main_context_query ().
2274  * 
2275  * Return value: %TRUE if some source is ready to be dispatched
2276  *               prior to polling.
2277  **/
2278 gboolean
2279 g_main_context_prepare (GMainContext *context,
2280                         gint         *priority)
2281 {
2282   gint i;
2283   gint n_ready = 0;
2284   gint current_priority = G_MAXINT;
2285   GSource *source;
2286
2287   if (context == NULL)
2288     context = g_main_context_default ();
2289   
2290   LOCK_CONTEXT (context);
2291
2292   context->time_is_current = FALSE;
2293
2294   if (context->in_check_or_prepare)
2295     {
2296       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2297                  "prepare() member.");
2298       UNLOCK_CONTEXT (context);
2299       return FALSE;
2300     }
2301
2302 #ifdef G_THREADS_ENABLED
2303   if (context->poll_waiting)
2304     {
2305       g_warning("g_main_context_prepare(): main loop already active in another thread");
2306       UNLOCK_CONTEXT (context);
2307       return FALSE;
2308     }
2309   
2310   context->poll_waiting = TRUE;
2311 #endif /* G_THREADS_ENABLED */
2312
2313 #if 0
2314   /* If recursing, finish up current dispatch, before starting over */
2315   if (context->pending_dispatches)
2316     {
2317       if (dispatch)
2318         g_main_dispatch (context, &current_time);
2319       
2320       UNLOCK_CONTEXT (context);
2321       return TRUE;
2322     }
2323 #endif
2324
2325   /* If recursing, clear list of pending dispatches */
2326
2327   for (i = 0; i < context->pending_dispatches->len; i++)
2328     {
2329       if (context->pending_dispatches->pdata[i])
2330         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2331     }
2332   g_ptr_array_set_size (context->pending_dispatches, 0);
2333   
2334   /* Prepare all sources */
2335
2336   context->timeout = -1;
2337   
2338   source = next_valid_source (context, NULL);
2339   while (source)
2340     {
2341       gint source_timeout = -1;
2342
2343       if ((n_ready > 0) && (source->priority > current_priority))
2344         {
2345           SOURCE_UNREF (source, context);
2346           break;
2347         }
2348       if (SOURCE_BLOCKED (source))
2349         goto next;
2350
2351       if (!(source->flags & G_SOURCE_READY))
2352         {
2353           gboolean result;
2354           gboolean (*prepare)  (GSource  *source, 
2355                                 gint     *timeout);
2356
2357           prepare = source->source_funcs->prepare;
2358           context->in_check_or_prepare++;
2359           UNLOCK_CONTEXT (context);
2360
2361           result = (*prepare) (source, &source_timeout);
2362
2363           LOCK_CONTEXT (context);
2364           context->in_check_or_prepare--;
2365
2366           if (result)
2367             source->flags |= G_SOURCE_READY;
2368         }
2369
2370       if (source->flags & G_SOURCE_READY)
2371         {
2372           n_ready++;
2373           current_priority = source->priority;
2374           context->timeout = 0;
2375         }
2376       
2377       if (source_timeout >= 0)
2378         {
2379           if (context->timeout < 0)
2380             context->timeout = source_timeout;
2381           else
2382             context->timeout = MIN (context->timeout, source_timeout);
2383         }
2384
2385     next:
2386       source = next_valid_source (context, source);
2387     }
2388
2389   UNLOCK_CONTEXT (context);
2390   
2391   if (priority)
2392     *priority = current_priority;
2393   
2394   return (n_ready > 0);
2395 }
2396
2397 /**
2398  * g_main_context_query:
2399  * @context: a #GMainContext
2400  * @max_priority: maximum priority source to check
2401  * @timeout_: location to store timeout to be used in polling
2402  * @fds: location to store #GPollFD records that need to be polled.
2403  * @n_fds: length of @fds.
2404  * 
2405  * Determines information necessary to poll this main loop.
2406  * 
2407  * Return value: the number of records actually stored in @fds,
2408  *   or, if more than @n_fds records need to be stored, the number
2409  *   of records that need to be stored.
2410  **/
2411 gint
2412 g_main_context_query (GMainContext *context,
2413                       gint          max_priority,
2414                       gint         *timeout,
2415                       GPollFD      *fds,
2416                       gint          n_fds)
2417 {
2418   gint n_poll;
2419   GPollRec *pollrec;
2420   
2421   LOCK_CONTEXT (context);
2422
2423   pollrec = context->poll_records;
2424   n_poll = 0;
2425   while (pollrec && max_priority >= pollrec->priority)
2426     {
2427       /* We need to include entries with fd->events == 0 in the array because
2428        * otherwise if the application changes fd->events behind our back and 
2429        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2430        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2431        * this API, but it occurs in practice.) */
2432       if (n_poll < n_fds)
2433         {
2434           fds[n_poll].fd = pollrec->fd->fd;
2435           /* In direct contradiction to the Unix98 spec, IRIX runs into
2436            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2437            * flags in the events field of the pollfd while it should
2438            * just ignoring them. So we mask them out here.
2439            */
2440           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2441           fds[n_poll].revents = 0;
2442         }
2443
2444       pollrec = pollrec->next;
2445       n_poll++;
2446     }
2447
2448 #ifdef G_THREADS_ENABLED
2449   context->poll_changed = FALSE;
2450 #endif
2451   
2452   if (timeout)
2453     {
2454       *timeout = context->timeout;
2455       if (*timeout != 0)
2456         context->time_is_current = FALSE;
2457     }
2458   
2459   UNLOCK_CONTEXT (context);
2460
2461   return n_poll;
2462 }
2463
2464 /**
2465  * g_main_context_check:
2466  * @context: a #GMainContext
2467  * @max_priority: the maximum numerical priority of sources to check
2468  * @fds: array of #GPollFD's that was passed to the last call to
2469  *       g_main_context_query()
2470  * @n_fds: return value of g_main_context_query()
2471  * 
2472  * Passes the results of polling back to the main loop.
2473  * 
2474  * Return value: %TRUE if some sources are ready to be dispatched.
2475  **/
2476 gboolean
2477 g_main_context_check (GMainContext *context,
2478                       gint          max_priority,
2479                       GPollFD      *fds,
2480                       gint          n_fds)
2481 {
2482   GSource *source;
2483   GPollRec *pollrec;
2484   gint n_ready = 0;
2485   gint i;
2486    
2487   LOCK_CONTEXT (context);
2488
2489   if (context->in_check_or_prepare)
2490     {
2491       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2492                  "prepare() member.");
2493       UNLOCK_CONTEXT (context);
2494       return FALSE;
2495     }
2496   
2497 #ifdef G_THREADS_ENABLED
2498   if (!context->poll_waiting)
2499     {
2500 #ifndef G_OS_WIN32
2501       gchar a;
2502       read (context->wake_up_pipe[0], &a, 1);
2503 #endif
2504     }
2505   else
2506     context->poll_waiting = FALSE;
2507
2508   /* If the set of poll file descriptors changed, bail out
2509    * and let the main loop rerun
2510    */
2511   if (context->poll_changed)
2512     {
2513       UNLOCK_CONTEXT (context);
2514       return FALSE;
2515     }
2516 #endif /* G_THREADS_ENABLED */
2517   
2518   pollrec = context->poll_records;
2519   i = 0;
2520   while (i < n_fds)
2521     {
2522       if (pollrec->fd->events)
2523         pollrec->fd->revents = fds[i].revents;
2524
2525       pollrec = pollrec->next;
2526       i++;
2527     }
2528
2529   source = next_valid_source (context, NULL);
2530   while (source)
2531     {
2532       if ((n_ready > 0) && (source->priority > max_priority))
2533         {
2534           SOURCE_UNREF (source, context);
2535           break;
2536         }
2537       if (SOURCE_BLOCKED (source))
2538         goto next;
2539
2540       if (!(source->flags & G_SOURCE_READY))
2541         {
2542           gboolean result;
2543           gboolean (*check) (GSource  *source);
2544
2545           check = source->source_funcs->check;
2546           
2547           context->in_check_or_prepare++;
2548           UNLOCK_CONTEXT (context);
2549           
2550           result = (*check) (source);
2551           
2552           LOCK_CONTEXT (context);
2553           context->in_check_or_prepare--;
2554           
2555           if (result)
2556             source->flags |= G_SOURCE_READY;
2557         }
2558
2559       if (source->flags & G_SOURCE_READY)
2560         {
2561           source->ref_count++;
2562           g_ptr_array_add (context->pending_dispatches, source);
2563
2564           n_ready++;
2565
2566           /* never dispatch sources with less priority than the first
2567            * one we choose to dispatch
2568            */
2569           max_priority = source->priority;
2570         }
2571
2572     next:
2573       source = next_valid_source (context, source);
2574     }
2575
2576   UNLOCK_CONTEXT (context);
2577
2578   return n_ready > 0;
2579 }
2580
2581 /**
2582  * g_main_context_dispatch:
2583  * @context: a #GMainContext
2584  * 
2585  * Dispatches all pending sources.
2586  **/
2587 void
2588 g_main_context_dispatch (GMainContext *context)
2589 {
2590   LOCK_CONTEXT (context);
2591
2592   if (context->pending_dispatches->len > 0)
2593     {
2594       g_main_dispatch (context);
2595     }
2596
2597   UNLOCK_CONTEXT (context);
2598 }
2599
2600 /* HOLDS context lock */
2601 static gboolean
2602 g_main_context_iterate (GMainContext *context,
2603                         gboolean      block,
2604                         gboolean      dispatch,
2605                         GThread      *self)
2606 {
2607   gint max_priority;
2608   gint timeout;
2609   gboolean some_ready;
2610   gint nfds, allocated_nfds;
2611   GPollFD *fds = NULL;
2612
2613   UNLOCK_CONTEXT (context);
2614
2615 #ifdef G_THREADS_ENABLED
2616   if (!g_main_context_acquire (context))
2617     {
2618       gboolean got_ownership;
2619
2620       LOCK_CONTEXT (context);
2621
2622       g_return_val_if_fail (g_thread_supported (), FALSE);
2623
2624       if (!block)
2625         return FALSE;
2626
2627       if (!context->cond)
2628         context->cond = g_cond_new ();
2629
2630       got_ownership = g_main_context_wait (context,
2631                                            context->cond,
2632                                            g_static_mutex_get_mutex (&context->mutex));
2633
2634       if (!got_ownership)
2635         return FALSE;
2636     }
2637   else
2638     LOCK_CONTEXT (context);
2639 #endif /* G_THREADS_ENABLED */
2640   
2641   if (!context->cached_poll_array)
2642     {
2643       context->cached_poll_array_size = context->n_poll_records;
2644       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
2645     }
2646
2647   allocated_nfds = context->cached_poll_array_size;
2648   fds = context->cached_poll_array;
2649   
2650   UNLOCK_CONTEXT (context);
2651
2652   g_main_context_prepare (context, &max_priority); 
2653   
2654   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
2655                                        allocated_nfds)) > allocated_nfds)
2656     {
2657       LOCK_CONTEXT (context);
2658       g_free (fds);
2659       context->cached_poll_array_size = allocated_nfds = nfds;
2660       context->cached_poll_array = fds = g_new (GPollFD, nfds);
2661       UNLOCK_CONTEXT (context);
2662     }
2663
2664   if (!block)
2665     timeout = 0;
2666   
2667   g_main_context_poll (context, timeout, max_priority, fds, nfds);
2668   
2669   some_ready = g_main_context_check (context, max_priority, fds, nfds);
2670   
2671   if (dispatch)
2672     g_main_context_dispatch (context);
2673   
2674 #ifdef G_THREADS_ENABLED
2675   g_main_context_release (context);
2676 #endif /* G_THREADS_ENABLED */    
2677
2678   LOCK_CONTEXT (context);
2679
2680   return some_ready;
2681 }
2682
2683 /**
2684  * g_main_context_pending:
2685  * @context: a #GMainContext (if %NULL, the default context will be used)
2686  *
2687  * Checks if any sources have pending events for the given context.
2688  * 
2689  * Return value: %TRUE if events are pending.
2690  **/
2691 gboolean 
2692 g_main_context_pending (GMainContext *context)
2693 {
2694   gboolean retval;
2695
2696   if (!context)
2697     context = g_main_context_default();
2698
2699   LOCK_CONTEXT (context);
2700   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
2701   UNLOCK_CONTEXT (context);
2702   
2703   return retval;
2704 }
2705
2706 /**
2707  * g_main_context_iteration:
2708  * @context: a #GMainContext (if %NULL, the default context will be used) 
2709  * @may_block: whether the call may block.
2710  * 
2711  * Runs a single iteration for the given main loop. This involves
2712  * checking to see if any event sources are ready to be processed,
2713  * then if no events sources are ready and @may_block is %TRUE, waiting
2714  * for a source to become ready, then dispatching the highest priority
2715  * events sources that are ready. Otherwise, if @may_block is %FALSE 
2716  * sources are not waited to become ready, only those highest priority 
2717  * events sources will be dispatched (if any), that are ready at this 
2718  * given moment without further waiting.
2719  *
2720  * Note that even when @may_block is %TRUE, it is still possible for 
2721  * g_main_context_iteration() to return %FALSE, since the the wait may 
2722  * be interrupted for other reasons than an event source becoming ready.
2723  * 
2724  * Return value: %TRUE if events were dispatched.
2725  **/
2726 gboolean
2727 g_main_context_iteration (GMainContext *context, gboolean may_block)
2728 {
2729   gboolean retval;
2730
2731   if (!context)
2732     context = g_main_context_default();
2733   
2734   LOCK_CONTEXT (context);
2735   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
2736   UNLOCK_CONTEXT (context);
2737   
2738   return retval;
2739 }
2740
2741 /**
2742  * g_main_loop_new:
2743  * @context: a #GMainContext  (if %NULL, the default context will be used).
2744  * @is_running: set to %TRUE to indicate that the loop is running. This
2745  * is not very important since calling g_main_loop_run() will set this to
2746  * %TRUE anyway.
2747  * 
2748  * Creates a new #GMainLoop structure.
2749  * 
2750  * Return value: a new #GMainLoop.
2751  **/
2752 GMainLoop *
2753 g_main_loop_new (GMainContext *context,
2754                  gboolean      is_running)
2755 {
2756   GMainLoop *loop;
2757
2758   if (!context)
2759     context = g_main_context_default();
2760   
2761   g_main_context_ref (context);
2762
2763   loop = g_new0 (GMainLoop, 1);
2764   loop->context = context;
2765   loop->is_running = is_running != FALSE;
2766   loop->ref_count = 1;
2767   
2768   return loop;
2769 }
2770
2771 /**
2772  * g_main_loop_ref:
2773  * @loop: a #GMainLoop
2774  * 
2775  * Increases the reference count on a #GMainLoop object by one.
2776  * 
2777  * Return value: @loop
2778  **/
2779 GMainLoop *
2780 g_main_loop_ref (GMainLoop *loop)
2781 {
2782   g_return_val_if_fail (loop != NULL, NULL);
2783   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2784
2785   g_atomic_int_inc (&loop->ref_count);
2786
2787   return loop;
2788 }
2789
2790 /**
2791  * g_main_loop_unref:
2792  * @loop: a #GMainLoop
2793  * 
2794  * Decreases the reference count on a #GMainLoop object by one. If
2795  * the result is zero, free the loop and free all associated memory.
2796  **/
2797 void
2798 g_main_loop_unref (GMainLoop *loop)
2799 {
2800   g_return_if_fail (loop != NULL);
2801   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2802
2803   if (!g_atomic_int_dec_and_test (&loop->ref_count))
2804     return;
2805
2806   g_main_context_unref (loop->context);
2807   g_free (loop);
2808 }
2809
2810 /**
2811  * g_main_loop_run:
2812  * @loop: a #GMainLoop
2813  * 
2814  * Runs a main loop until g_main_loop_quit() is called on the loop.
2815  * If this is called for the thread of the loop's #GMainContext,
2816  * it will process events from the loop, otherwise it will
2817  * simply wait.
2818  **/
2819 void 
2820 g_main_loop_run (GMainLoop *loop)
2821 {
2822   GThread *self = G_THREAD_SELF;
2823
2824   g_return_if_fail (loop != NULL);
2825   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2826
2827 #ifdef G_THREADS_ENABLED
2828   if (!g_main_context_acquire (loop->context))
2829     {
2830       gboolean got_ownership = FALSE;
2831       
2832       /* Another thread owns this context */
2833       if (!g_thread_supported ())
2834         {
2835           g_warning ("g_main_loop_run() was called from second thread but "
2836                      "g_thread_init() was never called.");
2837           return;
2838         }
2839       
2840       LOCK_CONTEXT (loop->context);
2841
2842       g_atomic_int_inc (&loop->ref_count);
2843
2844       if (!loop->is_running)
2845         loop->is_running = TRUE;
2846
2847       if (!loop->context->cond)
2848         loop->context->cond = g_cond_new ();
2849           
2850       while (loop->is_running && !got_ownership)
2851         got_ownership = g_main_context_wait (loop->context,
2852                                              loop->context->cond,
2853                                              g_static_mutex_get_mutex (&loop->context->mutex));
2854       
2855       if (!loop->is_running)
2856         {
2857           UNLOCK_CONTEXT (loop->context);
2858           if (got_ownership)
2859             g_main_context_release (loop->context);
2860           g_main_loop_unref (loop);
2861           return;
2862         }
2863
2864       g_assert (got_ownership);
2865     }
2866   else
2867     LOCK_CONTEXT (loop->context);
2868 #endif /* G_THREADS_ENABLED */ 
2869
2870   if (loop->context->in_check_or_prepare)
2871     {
2872       g_warning ("g_main_loop_run(): called recursively from within a source's "
2873                  "check() or prepare() member, iteration not possible.");
2874       return;
2875     }
2876
2877   g_atomic_int_inc (&loop->ref_count);
2878   loop->is_running = TRUE;
2879   while (loop->is_running)
2880     g_main_context_iterate (loop->context, TRUE, TRUE, self);
2881
2882   UNLOCK_CONTEXT (loop->context);
2883   
2884 #ifdef G_THREADS_ENABLED
2885   g_main_context_release (loop->context);
2886 #endif /* G_THREADS_ENABLED */    
2887   
2888   g_main_loop_unref (loop);
2889 }
2890
2891 /**
2892  * g_main_loop_quit:
2893  * @loop: a #GMainLoop
2894  * 
2895  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
2896  * for the loop will return. 
2897  *
2898  * Note that sources that have already been dispatched when 
2899  * g_main_loop_quit() is called will still be executed.
2900  **/
2901 void 
2902 g_main_loop_quit (GMainLoop *loop)
2903 {
2904   g_return_if_fail (loop != NULL);
2905   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
2906
2907   LOCK_CONTEXT (loop->context);
2908   loop->is_running = FALSE;
2909   g_main_context_wakeup_unlocked (loop->context);
2910
2911 #ifdef G_THREADS_ENABLED
2912   if (loop->context->cond)
2913     g_cond_broadcast (loop->context->cond);
2914 #endif /* G_THREADS_ENABLED */
2915
2916   UNLOCK_CONTEXT (loop->context);
2917 }
2918
2919 /**
2920  * g_main_loop_is_running:
2921  * @loop: a #GMainLoop.
2922  * 
2923  * Checks to see if the main loop is currently being run via g_main_loop_run().
2924  * 
2925  * Return value: %TRUE if the mainloop is currently being run.
2926  **/
2927 gboolean
2928 g_main_loop_is_running (GMainLoop *loop)
2929 {
2930   g_return_val_if_fail (loop != NULL, FALSE);
2931   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
2932
2933   return loop->is_running;
2934 }
2935
2936 /**
2937  * g_main_loop_get_context:
2938  * @loop: a #GMainLoop.
2939  * 
2940  * Returns the #GMainContext of @loop.
2941  * 
2942  * Return value: the #GMainContext of @loop
2943  **/
2944 GMainContext *
2945 g_main_loop_get_context (GMainLoop *loop)
2946 {
2947   g_return_val_if_fail (loop != NULL, NULL);
2948   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
2949  
2950   return loop->context;
2951 }
2952
2953 /* HOLDS: context's lock */
2954 static void
2955 g_main_context_poll (GMainContext *context,
2956                      gint          timeout,
2957                      gint          priority,
2958                      GPollFD      *fds,
2959                      gint          n_fds)
2960 {
2961 #ifdef  G_MAIN_POLL_DEBUG
2962   GTimer *poll_timer;
2963   GPollRec *pollrec;
2964   gint i;
2965 #endif
2966
2967   GPollFunc poll_func;
2968
2969   if (n_fds || timeout != 0)
2970     {
2971 #ifdef  G_MAIN_POLL_DEBUG
2972       if (_g_main_poll_debug)
2973         {
2974           g_print ("polling context=%p n=%d timeout=%d\n",
2975                    context, n_fds, timeout);
2976           poll_timer = g_timer_new ();
2977         }
2978 #endif
2979
2980       LOCK_CONTEXT (context);
2981
2982       poll_func = context->poll_func;
2983       
2984       UNLOCK_CONTEXT (context);
2985       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
2986         {
2987 #ifndef G_OS_WIN32
2988           g_warning ("poll(2) failed due to: %s.",
2989                      g_strerror (errno));
2990 #else
2991           /* If g_poll () returns -1, it has already called g_warning() */
2992 #endif
2993         }
2994       
2995 #ifdef  G_MAIN_POLL_DEBUG
2996       if (_g_main_poll_debug)
2997         {
2998           LOCK_CONTEXT (context);
2999
3000           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3001                    n_fds,
3002                    timeout,
3003                    g_timer_elapsed (poll_timer, NULL));
3004           g_timer_destroy (poll_timer);
3005           pollrec = context->poll_records;
3006
3007           while (pollrec != NULL)
3008             {
3009               i = 0;
3010               while (i < n_fds)
3011                 {
3012                   if (fds[i].fd == pollrec->fd->fd &&
3013                       pollrec->fd->events &&
3014                       fds[i].revents)
3015                     {
3016                       g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3017                       if (fds[i].revents & G_IO_IN)
3018                         g_print ("i");
3019                       if (fds[i].revents & G_IO_OUT)
3020                         g_print ("o");
3021                       if (fds[i].revents & G_IO_PRI)
3022                         g_print ("p");
3023                       if (fds[i].revents & G_IO_ERR)
3024                         g_print ("e");
3025                       if (fds[i].revents & G_IO_HUP)
3026                         g_print ("h");
3027                       if (fds[i].revents & G_IO_NVAL)
3028                         g_print ("n");
3029                       g_print ("]");
3030                     }
3031                   i++;
3032                 }
3033               pollrec = pollrec->next;
3034             }
3035           g_print ("\n");
3036
3037           UNLOCK_CONTEXT (context);
3038         }
3039 #endif
3040     } /* if (n_fds || timeout != 0) */
3041 }
3042
3043 /**
3044  * g_main_context_add_poll:
3045  * @context: a #GMainContext (or %NULL for the default context)
3046  * @fd: a #GPollFD structure holding information about a file
3047  *      descriptor to watch.
3048  * @priority: the priority for this file descriptor which should be
3049  *      the same as the priority used for g_source_attach() to ensure that the
3050  *      file descriptor is polled whenever the results may be needed.
3051  * 
3052  * Adds a file descriptor to the set of file descriptors polled for
3053  * this context. This will very seldomly be used directly. Instead
3054  * a typical event source will use g_source_add_poll() instead.
3055  **/
3056 void
3057 g_main_context_add_poll (GMainContext *context,
3058                          GPollFD      *fd,
3059                          gint          priority)
3060 {
3061   if (!context)
3062     context = g_main_context_default ();
3063   
3064   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3065   g_return_if_fail (fd);
3066
3067   LOCK_CONTEXT (context);
3068   g_main_context_add_poll_unlocked (context, priority, fd);
3069   UNLOCK_CONTEXT (context);
3070 }
3071
3072 /* HOLDS: main_loop_lock */
3073 static void 
3074 g_main_context_add_poll_unlocked (GMainContext *context,
3075                                   gint          priority,
3076                                   GPollFD      *fd)
3077 {
3078   GPollRec *lastrec, *pollrec;
3079   GPollRec *newrec = g_slice_new (GPollRec);
3080
3081   /* This file descriptor may be checked before we ever poll */
3082   fd->revents = 0;
3083   newrec->fd = fd;
3084   newrec->priority = priority;
3085
3086   lastrec = NULL;
3087   pollrec = context->poll_records;
3088   while (pollrec && priority >= pollrec->priority)
3089     {
3090       lastrec = pollrec;
3091       pollrec = pollrec->next;
3092     }
3093   
3094   if (lastrec)
3095     lastrec->next = newrec;
3096   else
3097     context->poll_records = newrec;
3098
3099   newrec->next = pollrec;
3100
3101   context->n_poll_records++;
3102
3103 #ifdef G_THREADS_ENABLED
3104   context->poll_changed = TRUE;
3105
3106   /* Now wake up the main loop if it is waiting in the poll() */
3107   g_main_context_wakeup_unlocked (context);
3108 #endif
3109 }
3110
3111 /**
3112  * g_main_context_remove_poll:
3113  * @context:a #GMainContext 
3114  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3115  * 
3116  * Removes file descriptor from the set of file descriptors to be
3117  * polled for a particular context.
3118  **/
3119 void
3120 g_main_context_remove_poll (GMainContext *context,
3121                             GPollFD      *fd)
3122 {
3123   if (!context)
3124     context = g_main_context_default ();
3125   
3126   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3127   g_return_if_fail (fd);
3128
3129   LOCK_CONTEXT (context);
3130   g_main_context_remove_poll_unlocked (context, fd);
3131   UNLOCK_CONTEXT (context);
3132 }
3133
3134 static void
3135 g_main_context_remove_poll_unlocked (GMainContext *context,
3136                                      GPollFD      *fd)
3137 {
3138   GPollRec *pollrec, *lastrec;
3139
3140   lastrec = NULL;
3141   pollrec = context->poll_records;
3142
3143   while (pollrec)
3144     {
3145       if (pollrec->fd == fd)
3146         {
3147           if (lastrec != NULL)
3148             lastrec->next = pollrec->next;
3149           else
3150             context->poll_records = pollrec->next;
3151
3152           g_slice_free (GPollRec, pollrec);
3153
3154           context->n_poll_records--;
3155           break;
3156         }
3157       lastrec = pollrec;
3158       pollrec = pollrec->next;
3159     }
3160
3161 #ifdef G_THREADS_ENABLED
3162   context->poll_changed = TRUE;
3163   
3164   /* Now wake up the main loop if it is waiting in the poll() */
3165   g_main_context_wakeup_unlocked (context);
3166 #endif
3167 }
3168
3169 /**
3170  * g_source_get_current_time:
3171  * @source:  a #GSource
3172  * @timeval: #GTimeVal structure in which to store current time.
3173  * 
3174  * Gets the "current time" to be used when checking 
3175  * this source. The advantage of calling this function over
3176  * calling g_get_current_time() directly is that when 
3177  * checking multiple sources, GLib can cache a single value
3178  * instead of having to repeatedly get the system time.
3179  **/
3180 void
3181 g_source_get_current_time (GSource  *source,
3182                            GTimeVal *timeval)
3183 {
3184   GMainContext *context;
3185   
3186   g_return_if_fail (source->context != NULL);
3187  
3188   context = source->context;
3189
3190   LOCK_CONTEXT (context);
3191
3192   if (!context->time_is_current)
3193     {
3194       g_get_current_time (&context->current_time);
3195       context->time_is_current = TRUE;
3196     }
3197   
3198   *timeval = context->current_time;
3199   
3200   UNLOCK_CONTEXT (context);
3201 }
3202
3203 /**
3204  * g_main_context_set_poll_func:
3205  * @context: a #GMainContext
3206  * @func: the function to call to poll all file descriptors
3207  * 
3208  * Sets the function to use to handle polling of file descriptors. It
3209  * will be used instead of the poll() system call 
3210  * (or GLib's replacement function, which is used where 
3211  * poll() isn't available).
3212  *
3213  * This function could possibly be used to integrate the GLib event
3214  * loop with an external event loop.
3215  **/
3216 void
3217 g_main_context_set_poll_func (GMainContext *context,
3218                               GPollFunc     func)
3219 {
3220   if (!context)
3221     context = g_main_context_default ();
3222   
3223   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3224
3225   LOCK_CONTEXT (context);
3226   
3227   if (func)
3228     context->poll_func = func;
3229   else
3230     context->poll_func = g_poll;
3231
3232   UNLOCK_CONTEXT (context);
3233 }
3234
3235 /**
3236  * g_main_context_get_poll_func:
3237  * @context: a #GMainContext
3238  * 
3239  * Gets the poll function set by g_main_context_set_poll_func().
3240  * 
3241  * Return value: the poll function
3242  **/
3243 GPollFunc
3244 g_main_context_get_poll_func (GMainContext *context)
3245 {
3246   GPollFunc result;
3247   
3248   if (!context)
3249     context = g_main_context_default ();
3250   
3251   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3252
3253   LOCK_CONTEXT (context);
3254   result = context->poll_func;
3255   UNLOCK_CONTEXT (context);
3256
3257   return result;
3258 }
3259
3260 /* HOLDS: context's lock */
3261 /* Wake the main loop up from a poll() */
3262 static void
3263 g_main_context_wakeup_unlocked (GMainContext *context)
3264 {
3265 #ifdef G_THREADS_ENABLED
3266   if (g_thread_supported() && context->poll_waiting)
3267     {
3268       context->poll_waiting = FALSE;
3269 #ifndef G_OS_WIN32
3270       write (context->wake_up_pipe[1], "A", 1);
3271 #else
3272       ReleaseSemaphore (context->wake_up_semaphore, 1, NULL);
3273 #endif
3274     }
3275 #endif
3276 }
3277
3278 /**
3279  * g_main_context_wakeup:
3280  * @context: a #GMainContext
3281  * 
3282  * If @context is currently waiting in a poll(), interrupt
3283  * the poll(), and continue the iteration process.
3284  **/
3285 void
3286 g_main_context_wakeup (GMainContext *context)
3287 {
3288   if (!context)
3289     context = g_main_context_default ();
3290   
3291   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3292
3293   LOCK_CONTEXT (context);
3294   g_main_context_wakeup_unlocked (context);
3295   UNLOCK_CONTEXT (context);
3296 }
3297
3298 /**
3299  * g_main_context_is_owner:
3300  * @context: a #GMainContext
3301  * 
3302  * Determines whether this thread holds the (recursive)
3303  * ownership of this #GMaincontext. This is useful to
3304  * know before waiting on another thread that may be
3305  * blocking to get ownership of @context.
3306  *
3307  * Returns: %TRUE if current thread is owner of @context.
3308  *
3309  * Since: 2.10
3310  **/
3311 gboolean
3312 g_main_context_is_owner (GMainContext *context)
3313 {
3314   gboolean is_owner;
3315
3316   if (!context)
3317     context = g_main_context_default ();
3318
3319 #ifdef G_THREADS_ENABLED
3320   LOCK_CONTEXT (context);
3321   is_owner = context->owner == G_THREAD_SELF;
3322   UNLOCK_CONTEXT (context);
3323 #else
3324   is_owner = TRUE;
3325 #endif
3326
3327   return is_owner;
3328 }
3329
3330 /* Timeouts */
3331
3332 static void
3333 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3334                           GTimeVal       *current_time)
3335 {
3336   guint seconds = timeout_source->interval / 1000;
3337   guint msecs = timeout_source->interval - seconds * 1000;
3338
3339   timeout_source->expiration.tv_sec = current_time->tv_sec + seconds;
3340   timeout_source->expiration.tv_usec = current_time->tv_usec + msecs * 1000;
3341   if (timeout_source->expiration.tv_usec >= 1000000)
3342     {
3343       timeout_source->expiration.tv_usec -= 1000000;
3344       timeout_source->expiration.tv_sec++;
3345     }
3346   if (timer_perturb==-1)
3347     {
3348       /*
3349        * we want a per machine/session unique 'random' value; try the dbus
3350        * address first, that has a UUID in it. If there is no dbus, use the
3351        * hostname for hashing.
3352        */
3353       const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3354       if (!session_bus_address)
3355         session_bus_address = g_getenv ("HOSTNAME");
3356       if (session_bus_address)
3357         timer_perturb = ABS ((gint) g_str_hash (session_bus_address));
3358       else
3359         timer_perturb = 0;
3360     }
3361   if (timeout_source->granularity)
3362     {
3363       gint remainder;
3364       gint gran; /* in usecs */
3365       gint perturb;
3366
3367       gran = timeout_source->granularity * 1000;
3368       perturb = timer_perturb % gran;
3369       /*
3370        * We want to give each machine a per machine pertubation;
3371        * shift time back first, and forward later after the rounding
3372        */
3373
3374       timeout_source->expiration.tv_usec -= perturb;
3375       if (timeout_source->expiration.tv_usec < 0)
3376         {
3377           timeout_source->expiration.tv_usec += 1000000;
3378           timeout_source->expiration.tv_sec--;
3379         }
3380
3381       remainder = timeout_source->expiration.tv_usec % gran;
3382       if (remainder >= gran/4) /* round up */
3383         timeout_source->expiration.tv_usec += gran;
3384       timeout_source->expiration.tv_usec -= remainder;
3385       /* shift back */
3386       timeout_source->expiration.tv_usec += perturb;
3387
3388       /* the rounding may have overflown tv_usec */
3389       while (timeout_source->expiration.tv_usec > 1000000)
3390         {
3391           timeout_source->expiration.tv_usec -= 1000000;
3392           timeout_source->expiration.tv_sec++;
3393         }
3394     }
3395 }
3396
3397 static gboolean
3398 g_timeout_prepare (GSource *source,
3399                    gint    *timeout)
3400 {
3401   glong sec;
3402   glong msec;
3403   GTimeVal current_time;
3404   
3405   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3406
3407   g_source_get_current_time (source, &current_time);
3408
3409   sec = timeout_source->expiration.tv_sec - current_time.tv_sec;
3410   msec = (timeout_source->expiration.tv_usec - current_time.tv_usec) / 1000;
3411
3412   /* We do the following in a rather convoluted fashion to deal with
3413    * the fact that we don't have an integral type big enough to hold
3414    * the difference of two timevals in millseconds.
3415    */
3416   if (sec < 0 || (sec == 0 && msec < 0))
3417     msec = 0;
3418   else
3419     {
3420       glong interval_sec = timeout_source->interval / 1000;
3421       glong interval_msec = timeout_source->interval % 1000;
3422
3423       if (msec < 0)
3424         {
3425           msec += 1000;
3426           sec -= 1;
3427         }
3428       
3429       if (sec > interval_sec ||
3430           (sec == interval_sec && msec > interval_msec))
3431         {
3432           /* The system time has been set backwards, so we
3433            * reset the expiration time to now + timeout_source->interval;
3434            * this at least avoids hanging for long periods of time.
3435            */
3436           g_timeout_set_expiration (timeout_source, &current_time);
3437           msec = MIN (G_MAXINT, timeout_source->interval);
3438         }
3439       else
3440         {
3441           msec = MIN (G_MAXINT, (guint)msec + 1000 * (guint)sec);
3442         }
3443     }
3444
3445   *timeout = (gint)msec;
3446   
3447   return msec == 0;
3448 }
3449
3450 static gboolean 
3451 g_timeout_check (GSource *source)
3452 {
3453   GTimeVal current_time;
3454   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3455
3456   g_source_get_current_time (source, &current_time);
3457   
3458   return ((timeout_source->expiration.tv_sec < current_time.tv_sec) ||
3459           ((timeout_source->expiration.tv_sec == current_time.tv_sec) &&
3460            (timeout_source->expiration.tv_usec <= current_time.tv_usec)));
3461 }
3462
3463 static gboolean
3464 g_timeout_dispatch (GSource     *source,
3465                     GSourceFunc  callback,
3466                     gpointer     user_data)
3467 {
3468   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3469
3470   if (!callback)
3471     {
3472       g_warning ("Timeout source dispatched without callback\n"
3473                  "You must call g_source_set_callback().");
3474       return FALSE;
3475     }
3476  
3477   if (callback (user_data))
3478     {
3479       GTimeVal current_time;
3480
3481       g_source_get_current_time (source, &current_time);
3482       g_timeout_set_expiration (timeout_source, &current_time);
3483
3484       return TRUE;
3485     }
3486   else
3487     return FALSE;
3488 }
3489
3490 /**
3491  * g_timeout_source_new:
3492  * @interval: the timeout interval in milliseconds.
3493  * 
3494  * Creates a new timeout source.
3495  *
3496  * The source will not initially be associated with any #GMainContext
3497  * and must be added to one with g_source_attach() before it will be
3498  * executed.
3499  * 
3500  * Return value: the newly-created timeout source
3501  **/
3502 GSource *
3503 g_timeout_source_new (guint interval)
3504 {
3505   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3506   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3507   GTimeVal current_time;
3508
3509   timeout_source->interval = interval;
3510
3511   g_get_current_time (&current_time);
3512   g_timeout_set_expiration (timeout_source, &current_time);
3513   
3514   return source;
3515 }
3516
3517 /**
3518  * g_timeout_source_new_seconds:
3519  * @interval: the timeout interval in seconds
3520  *
3521  * Creates a new timeout source.
3522  *
3523  * The source will not initially be associated with any #GMainContext
3524  * and must be added to one with g_source_attach() before it will be
3525  * executed.
3526  *
3527  * The scheduling granularity/accuracy of this timeout source will be
3528  * in seconds.
3529  *
3530  * Return value: the newly-created timeout source
3531  *
3532  * Since: 2.14  
3533  **/
3534 GSource *
3535 g_timeout_source_new_seconds (guint interval)
3536 {
3537   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3538   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3539   GTimeVal current_time;
3540
3541   timeout_source->interval = 1000*interval;
3542   timeout_source->granularity = 1000;
3543
3544   g_get_current_time (&current_time);
3545   g_timeout_set_expiration (timeout_source, &current_time);
3546
3547   return source;
3548 }
3549
3550
3551 /**
3552  * g_timeout_add_full:
3553  * @priority: the priority of the timeout source. Typically this will be in
3554  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3555  * @interval: the time between calls to the function, in milliseconds
3556  *             (1/1000ths of a second)
3557  * @function: function to call
3558  * @data:     data to pass to @function
3559  * @notify:   function to call when the timeout is removed, or %NULL
3560  * 
3561  * Sets a function to be called at regular intervals, with the given
3562  * priority.  The function is called repeatedly until it returns
3563  * %FALSE, at which point the timeout is automatically destroyed and
3564  * the function will not be called again.  The @notify function is
3565  * called when the timeout is destroyed.  The first call to the
3566  * function will be at the end of the first @interval.
3567  *
3568  * Note that timeout functions may be delayed, due to the processing of other
3569  * event sources. Thus they should not be relied on for precise timing.
3570  * After each call to the timeout function, the time of the next
3571  * timeout is recalculated based on the current time and the given interval
3572  * (it does not try to 'catch up' time lost in delays).
3573  *
3574  * This internally creates a main loop source using g_timeout_source_new()
3575  * and attaches it to the main loop context using g_source_attach(). You can
3576  * do these steps manually if you need greater control.
3577  * 
3578  * Return value: the ID (greater than 0) of the event source.
3579  **/
3580 guint
3581 g_timeout_add_full (gint           priority,
3582                     guint          interval,
3583                     GSourceFunc    function,
3584                     gpointer       data,
3585                     GDestroyNotify notify)
3586 {
3587   GSource *source;
3588   guint id;
3589   
3590   g_return_val_if_fail (function != NULL, 0);
3591
3592   source = g_timeout_source_new (interval);
3593
3594   if (priority != G_PRIORITY_DEFAULT)
3595     g_source_set_priority (source, priority);
3596
3597   g_source_set_callback (source, function, data, notify);
3598   id = g_source_attach (source, NULL);
3599   g_source_unref (source);
3600
3601   return id;
3602 }
3603
3604 /**
3605  * g_timeout_add:
3606  * @interval: the time between calls to the function, in milliseconds
3607  *             (1/1000ths of a second)
3608  * @function: function to call
3609  * @data:     data to pass to @function
3610  * 
3611  * Sets a function to be called at regular intervals, with the default
3612  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
3613  * until it returns %FALSE, at which point the timeout is automatically
3614  * destroyed and the function will not be called again.  The first call
3615  * to the function will be at the end of the first @interval.
3616  *
3617  * Note that timeout functions may be delayed, due to the processing of other
3618  * event sources. Thus they should not be relied on for precise timing.
3619  * After each call to the timeout function, the time of the next
3620  * timeout is recalculated based on the current time and the given interval
3621  * (it does not try to 'catch up' time lost in delays).
3622  *
3623  * If you want to have a timer in the "seconds" range and do not care
3624  * about the exact time of the first call of the timer, use the
3625  * g_timeout_add_seconds() function; this function allows for more
3626  * optimizations and more efficient system power usage.
3627  *
3628  * This internally creates a main loop source using g_timeout_source_new()
3629  * and attaches it to the main loop context using g_source_attach(). You can
3630  * do these steps manually if you need greater control.
3631  * 
3632  * Return value: the ID (greater than 0) of the event source.
3633  **/
3634 guint
3635 g_timeout_add (guint32        interval,
3636                GSourceFunc    function,
3637                gpointer       data)
3638 {
3639   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
3640                              interval, function, data, NULL);
3641 }
3642
3643 /**
3644  * g_timeout_add_seconds_full:
3645  * @priority: the priority of the timeout source. Typically this will be in
3646  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3647  * @interval: the time between calls to the function, in seconds
3648  * @function: function to call
3649  * @data:     data to pass to @function
3650  * @notify:   function to call when the timeout is removed, or %NULL
3651  *
3652  * Sets a function to be called at regular intervals, with @priority.
3653  * The function is called repeatedly until it returns %FALSE, at which
3654  * point the timeout is automatically destroyed and the function will
3655  * not be called again.
3656  *
3657  * Unlike g_timeout_add(), this function operates at whole second granularity.
3658  * The initial starting point of the timer is determined by the implementation
3659  * and the implementation is expected to group multiple timers together so that
3660  * they fire all at the same time.
3661  * To allow this grouping, the @interval to the first timer is rounded
3662  * and can deviate up to one second from the specified interval.
3663  * Subsequent timer iterations will generally run at the specified interval.
3664  *
3665  * Note that timeout functions may be delayed, due to the processing of other
3666  * event sources. Thus they should not be relied on for precise timing.
3667  * After each call to the timeout function, the time of the next
3668  * timeout is recalculated based on the current time and the given @interval
3669  *
3670  * If you want timing more precise than whole seconds, use g_timeout_add()
3671  * instead.
3672  *
3673  * The grouping of timers to fire at the same time results in a more power
3674  * and CPU efficient behavior so if your timer is in multiples of seconds
3675  * and you don't require the first timer exactly one second from now, the
3676  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
3677  *
3678  * This internally creates a main loop source using 
3679  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3680  * using g_source_attach(). You can do these steps manually if you need 
3681  * greater control.
3682  * 
3683  * Return value: the ID (greater than 0) of the event source.
3684  *
3685  * Since: 2.14
3686  **/
3687 guint
3688 g_timeout_add_seconds_full (gint           priority,
3689                             guint32        interval,
3690                             GSourceFunc    function,
3691                             gpointer       data,
3692                             GDestroyNotify notify)
3693 {
3694   GSource *source;
3695   guint id;
3696
3697   g_return_val_if_fail (function != NULL, 0);
3698
3699   source = g_timeout_source_new_seconds (interval);
3700
3701   if (priority != G_PRIORITY_DEFAULT)
3702     g_source_set_priority (source, priority);
3703
3704   g_source_set_callback (source, function, data, notify);
3705   id = g_source_attach (source, NULL);
3706   g_source_unref (source);
3707
3708   return id;
3709 }
3710
3711 /**
3712  * g_timeout_add_seconds:
3713  * @interval: the time between calls to the function, in seconds
3714  * @function: function to call
3715  * @data: data to pass to @function
3716  *
3717  * Sets a function to be called at regular intervals with the default
3718  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
3719  * it returns %FALSE, at which point the timeout is automatically destroyed
3720  * and the function will not be called again.
3721  *
3722  * This internally creates a main loop source using 
3723  * g_timeout_source_new_seconds() and attaches it to the main loop context 
3724  * using g_source_attach(). You can do these steps manually if you need 
3725  * greater control. Also see g_timout_add_seconds_full().
3726  * 
3727  * Return value: the ID (greater than 0) of the event source.
3728  *
3729  * Since: 2.14
3730  **/
3731 guint
3732 g_timeout_add_seconds (guint       interval,
3733                        GSourceFunc function,
3734                        gpointer    data)
3735 {
3736   g_return_val_if_fail (function != NULL, 0);
3737
3738   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
3739 }
3740
3741 /* Child watch functions */
3742
3743 #ifdef G_OS_WIN32
3744
3745 static gboolean
3746 g_child_watch_prepare (GSource *source,
3747                        gint    *timeout)
3748 {
3749   *timeout = -1;
3750   return FALSE;
3751 }
3752
3753
3754 static gboolean 
3755 g_child_watch_check (GSource  *source)
3756 {
3757   GChildWatchSource *child_watch_source;
3758   gboolean child_exited;
3759
3760   child_watch_source = (GChildWatchSource *) source;
3761
3762   child_exited = child_watch_source->poll.revents & G_IO_IN;
3763
3764   if (child_exited)
3765     {
3766       DWORD child_status;
3767
3768       /*
3769        * Note: We do _not_ check for the special value of STILL_ACTIVE
3770        * since we know that the process has exited and doing so runs into
3771        * problems if the child process "happens to return STILL_ACTIVE(259)"
3772        * as Microsoft's Platform SDK puts it.
3773        */
3774       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
3775         {
3776           gchar *emsg = g_win32_error_message (GetLastError ());
3777           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
3778           g_free (emsg);
3779
3780           child_watch_source->child_status = -1;
3781         }
3782       else
3783         child_watch_source->child_status = child_status;
3784     }
3785
3786   return child_exited;
3787 }
3788
3789 #else /* G_OS_WIN32 */
3790
3791 static gboolean
3792 check_for_child_exited (GSource *source)
3793 {
3794   GChildWatchSource *child_watch_source;
3795   gint count;
3796
3797   /* protect against another SIGCHLD in the middle of this call */
3798   count = child_watch_count;
3799
3800   child_watch_source = (GChildWatchSource *) source;
3801
3802   if (child_watch_source->child_exited)
3803     return TRUE;
3804
3805   if (child_watch_source->count < count)
3806     {
3807       gint child_status;
3808
3809       if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
3810         {
3811           child_watch_source->child_status = child_status;
3812           child_watch_source->child_exited = TRUE;
3813         }
3814       child_watch_source->count = count;
3815     }
3816
3817   return child_watch_source->child_exited;
3818 }
3819
3820 static gboolean
3821 g_child_watch_prepare (GSource *source,
3822                        gint    *timeout)
3823 {
3824   *timeout = -1;
3825
3826   return check_for_child_exited (source);
3827 }
3828
3829
3830 static gboolean 
3831 g_child_watch_check (GSource  *source)
3832 {
3833   return check_for_child_exited (source);
3834 }
3835
3836 #endif /* G_OS_WIN32 */
3837
3838 static gboolean
3839 g_child_watch_dispatch (GSource    *source, 
3840                         GSourceFunc callback,
3841                         gpointer    user_data)
3842 {
3843   GChildWatchSource *child_watch_source;
3844   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
3845
3846   child_watch_source = (GChildWatchSource *) source;
3847
3848   if (!callback)
3849     {
3850       g_warning ("Child watch source dispatched without callback\n"
3851                  "You must call g_source_set_callback().");
3852       return FALSE;
3853     }
3854
3855   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
3856
3857   /* We never keep a child watch source around as the child is gone */
3858   return FALSE;
3859 }
3860
3861 #ifndef G_OS_WIN32
3862
3863 static void
3864 g_child_watch_signal_handler (int signum)
3865 {
3866   child_watch_count ++;
3867
3868   if (child_watch_init_state == CHILD_WATCH_INITIALIZED_THREADED)
3869     {
3870       write (child_watch_wake_up_pipe[1], "B", 1);
3871     }
3872   else
3873     {
3874       /* We count on the signal interrupting the poll in the same thread.
3875        */
3876     }
3877 }
3878  
3879 static void
3880 g_child_watch_source_init_single (void)
3881 {
3882   struct sigaction action;
3883
3884   g_assert (! g_thread_supported());
3885   g_assert (child_watch_init_state == CHILD_WATCH_UNINITIALIZED);
3886
3887   child_watch_init_state = CHILD_WATCH_INITIALIZED_SINGLE;
3888
3889   action.sa_handler = g_child_watch_signal_handler;
3890   sigemptyset (&action.sa_mask);
3891   action.sa_flags = SA_NOCLDSTOP;
3892   sigaction (SIGCHLD, &action, NULL);
3893 }
3894
3895 G_GNUC_NORETURN static gpointer
3896 child_watch_helper_thread (gpointer data) 
3897 {
3898   while (1)
3899     {
3900       gchar b[20];
3901       GSList *list;
3902
3903       read (child_watch_wake_up_pipe[0], b, 20);
3904
3905       /* We were woken up.  Wake up all other contexts in all other threads */
3906       G_LOCK (main_context_list);
3907       for (list = main_context_list; list; list = list->next)
3908         {
3909           GMainContext *context;
3910
3911           context = list->data;
3912           if (g_atomic_int_get (&context->ref_count) > 0)
3913             /* Due to racing conditions we can find ref_count == 0, in
3914              * that case, however, the context is still not destroyed
3915              * and no poll can be active, otherwise the ref_count
3916              * wouldn't be 0 */
3917             g_main_context_wakeup (context);
3918         }
3919       G_UNLOCK (main_context_list);
3920     }
3921 }
3922
3923 static void
3924 g_child_watch_source_init_multi_threaded (void)
3925 {
3926   GError *error = NULL;
3927   struct sigaction action;
3928
3929   g_assert (g_thread_supported());
3930
3931   if (pipe (child_watch_wake_up_pipe) < 0)
3932     g_error ("Cannot create wake up pipe: %s\n", g_strerror (errno));
3933   fcntl (child_watch_wake_up_pipe[1], F_SETFL, O_NONBLOCK | fcntl (child_watch_wake_up_pipe[1], F_GETFL));
3934
3935   /* We create a helper thread that polls on the wakeup pipe indefinitely */
3936   /* FIXME: Think this through for races */
3937   if (g_thread_create (child_watch_helper_thread, NULL, FALSE, &error) == NULL)
3938     g_error ("Cannot create a thread to monitor child exit status: %s\n", error->message);
3939   child_watch_init_state = CHILD_WATCH_INITIALIZED_THREADED;
3940  
3941   action.sa_handler = g_child_watch_signal_handler;
3942   sigemptyset (&action.sa_mask);
3943   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
3944   sigaction (SIGCHLD, &action, NULL);
3945 }
3946
3947 static void
3948 g_child_watch_source_init_promote_single_to_threaded (void)
3949 {
3950   g_child_watch_source_init_multi_threaded ();
3951 }
3952
3953 static void
3954 g_child_watch_source_init (void)
3955 {
3956   if (g_thread_supported())
3957     {
3958       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3959         g_child_watch_source_init_multi_threaded ();
3960       else if (child_watch_init_state == CHILD_WATCH_INITIALIZED_SINGLE)
3961         g_child_watch_source_init_promote_single_to_threaded ();
3962     }
3963   else
3964     {
3965       if (child_watch_init_state == CHILD_WATCH_UNINITIALIZED)
3966         g_child_watch_source_init_single ();
3967     }
3968 }
3969
3970 #endif /* !G_OS_WIN32 */
3971
3972 /**
3973  * g_child_watch_source_new:
3974  * @pid: process to watch. On POSIX the pid of a child process. On
3975  * Windows a handle for a process (which doesn't have to be a child).
3976  * 
3977  * Creates a new child_watch source.
3978  *
3979  * The source will not initially be associated with any #GMainContext
3980  * and must be added to one with g_source_attach() before it will be
3981  * executed.
3982  * 
3983  * Note that child watch sources can only be used in conjunction with
3984  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
3985  * flag is used.
3986  *
3987  * Note that on platforms where #GPid must be explicitly closed
3988  * (see g_spawn_close_pid()) @pid must not be closed while the
3989  * source is still active. Typically, you will want to call
3990  * g_spawn_close_pid() in the callback function for the source.
3991  *
3992  * Note further that using g_child_watch_source_new() is not 
3993  * compatible with calling <literal>waitpid(-1)</literal> in 
3994  * the application. Calling waitpid() for individual pids will
3995  * still work fine. 
3996  * 
3997  * Return value: the newly-created child watch source
3998  *
3999  * Since: 2.4
4000  **/
4001 GSource *
4002 g_child_watch_source_new (GPid pid)
4003 {
4004   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4005   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4006
4007 #ifdef G_OS_WIN32
4008   child_watch_source->poll.fd = (gintptr) pid;
4009   child_watch_source->poll.events = G_IO_IN;
4010
4011   g_source_add_poll (source, &child_watch_source->poll);
4012 #else /* G_OS_WIN32 */
4013   g_child_watch_source_init ();
4014 #endif /* G_OS_WIN32 */
4015
4016   child_watch_source->pid = pid;
4017
4018   return source;
4019 }
4020
4021 /**
4022  * g_child_watch_add_full:
4023  * @priority: the priority of the idle source. Typically this will be in the
4024  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4025  * @pid:      process to watch. On POSIX the pid of a child process. On
4026  * Windows a handle for a process (which doesn't have to be a child).
4027  * @function: function to call
4028  * @data:     data to pass to @function
4029  * @notify:   function to call when the idle is removed, or %NULL
4030  * 
4031  * Sets a function to be called when the child indicated by @pid 
4032  * exits, at the priority @priority.
4033  *
4034  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4035  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4036  * the spawn function for the child watching to work.
4037  * 
4038  * Note that on platforms where #GPid must be explicitly closed
4039  * (see g_spawn_close_pid()) @pid must not be closed while the
4040  * source is still active. Typically, you will want to call
4041  * g_spawn_close_pid() in the callback function for the source.
4042  * 
4043  * GLib supports only a single callback per process id.
4044  *
4045  * This internally creates a main loop source using 
4046  * g_child_watch_source_new() and attaches it to the main loop context 
4047  * using g_source_attach(). You can do these steps manually if you 
4048  * need greater control.
4049  *
4050  * Return value: the ID (greater than 0) of the event source.
4051  *
4052  * Since: 2.4
4053  **/
4054 guint
4055 g_child_watch_add_full (gint            priority,
4056                         GPid            pid,
4057                         GChildWatchFunc function,
4058                         gpointer        data,
4059                         GDestroyNotify  notify)
4060 {
4061   GSource *source;
4062   guint id;
4063   
4064   g_return_val_if_fail (function != NULL, 0);
4065
4066   source = g_child_watch_source_new (pid);
4067
4068   if (priority != G_PRIORITY_DEFAULT)
4069     g_source_set_priority (source, priority);
4070
4071   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4072   id = g_source_attach (source, NULL);
4073   g_source_unref (source);
4074
4075   return id;
4076 }
4077
4078 /**
4079  * g_child_watch_add:
4080  * @pid:      process id to watch. On POSIX the pid of a child process. On
4081  * Windows a handle for a process (which doesn't have to be a child).
4082  * @function: function to call
4083  * @data:     data to pass to @function
4084  * 
4085  * Sets a function to be called when the child indicated by @pid 
4086  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4087  * 
4088  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4089  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4090  * the spawn function for the child watching to work.
4091  * 
4092  * Note that on platforms where #GPid must be explicitly closed
4093  * (see g_spawn_close_pid()) @pid must not be closed while the
4094  * source is still active. Typically, you will want to call
4095  * g_spawn_close_pid() in the callback function for the source.
4096  *
4097  * GLib supports only a single callback per process id.
4098  *
4099  * This internally creates a main loop source using 
4100  * g_child_watch_source_new() and attaches it to the main loop context 
4101  * using g_source_attach(). You can do these steps manually if you 
4102  * need greater control.
4103  *
4104  * Return value: the ID (greater than 0) of the event source.
4105  *
4106  * Since: 2.4
4107  **/
4108 guint 
4109 g_child_watch_add (GPid            pid,
4110                    GChildWatchFunc function,
4111                    gpointer        data)
4112 {
4113   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4114 }
4115
4116
4117 /* Idle functions */
4118
4119 static gboolean 
4120 g_idle_prepare  (GSource  *source,
4121                  gint     *timeout)
4122 {
4123   *timeout = 0;
4124
4125   return TRUE;
4126 }
4127
4128 static gboolean 
4129 g_idle_check    (GSource  *source)
4130 {
4131   return TRUE;
4132 }
4133
4134 static gboolean
4135 g_idle_dispatch (GSource    *source, 
4136                  GSourceFunc callback,
4137                  gpointer    user_data)
4138 {
4139   if (!callback)
4140     {
4141       g_warning ("Idle source dispatched without callback\n"
4142                  "You must call g_source_set_callback().");
4143       return FALSE;
4144     }
4145   
4146   return callback (user_data);
4147 }
4148
4149 /**
4150  * g_idle_source_new:
4151  * 
4152  * Creates a new idle source.
4153  *
4154  * The source will not initially be associated with any #GMainContext
4155  * and must be added to one with g_source_attach() before it will be
4156  * executed. Note that the default priority for idle sources is
4157  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4158  * have a default priority of %G_PRIORITY_DEFAULT.
4159  * 
4160  * Return value: the newly-created idle source
4161  **/
4162 GSource *
4163 g_idle_source_new (void)
4164 {
4165   GSource *source;
4166
4167   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4168   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4169
4170   return source;
4171 }
4172
4173 /**
4174  * g_idle_add_full:
4175  * @priority: the priority of the idle source. Typically this will be in the
4176  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4177  * @function: function to call
4178  * @data:     data to pass to @function
4179  * @notify:   function to call when the idle is removed, or %NULL
4180  * 
4181  * Adds a function to be called whenever there are no higher priority
4182  * events pending.  If the function returns %FALSE it is automatically
4183  * removed from the list of event sources and will not be called again.
4184  * 
4185  * This internally creates a main loop source using g_idle_source_new()
4186  * and attaches it to the main loop context using g_source_attach(). 
4187  * You can do these steps manually if you need greater control.
4188  * 
4189  * Return value: the ID (greater than 0) of the event source.
4190  **/
4191 guint 
4192 g_idle_add_full (gint           priority,
4193                  GSourceFunc    function,
4194                  gpointer       data,
4195                  GDestroyNotify notify)
4196 {
4197   GSource *source;
4198   guint id;
4199   
4200   g_return_val_if_fail (function != NULL, 0);
4201
4202   source = g_idle_source_new ();
4203
4204   if (priority != G_PRIORITY_DEFAULT_IDLE)
4205     g_source_set_priority (source, priority);
4206
4207   g_source_set_callback (source, function, data, notify);
4208   id = g_source_attach (source, NULL);
4209   g_source_unref (source);
4210
4211   return id;
4212 }
4213
4214 /**
4215  * g_idle_add:
4216  * @function: function to call 
4217  * @data: data to pass to @function.
4218  * 
4219  * Adds a function to be called whenever there are no higher priority
4220  * events pending to the default main loop. The function is given the
4221  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4222  * returns %FALSE it is automatically removed from the list of event
4223  * sources and will not be called again.
4224  * 
4225  * This internally creates a main loop source using g_idle_source_new()
4226  * and attaches it to the main loop context using g_source_attach(). 
4227  * You can do these steps manually if you need greater control.
4228  * 
4229  * Return value: the ID (greater than 0) of the event source.
4230  **/
4231 guint 
4232 g_idle_add (GSourceFunc    function,
4233             gpointer       data)
4234 {
4235   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4236 }
4237
4238 /**
4239  * g_idle_remove_by_data:
4240  * @data: the data for the idle source's callback.
4241  * 
4242  * Removes the idle function with the given data.
4243  * 
4244  * Return value: %TRUE if an idle source was found and removed.
4245  **/
4246 gboolean
4247 g_idle_remove_by_data (gpointer data)
4248 {
4249   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4250 }
4251
4252 #define __G_MAIN_C__
4253 #include "galiasdef.c"