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