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