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