g_get_monotonic_time: fix race condition
[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  * It's important to note that POSIX %CLOCK_MONOTONIC does not count
2028  * time spent while the machine is suspended.
2029  *
2030  * On Windows, "limitations of the OS kernel" is a rather substantial
2031  * statement.  Depending on the configuration of the system, the wall
2032  * clock time is updated as infrequently as 64 times a second (which
2033  * is approximately every 16ms).
2034  *
2035  * Returns: the monotonic time, in microseconds
2036  *
2037  * Since: 2.28
2038  **/
2039 gint64
2040 g_get_monotonic_time (void)
2041 {
2042 #ifdef HAVE_CLOCK_GETTIME
2043   /* librt clock_gettime() is our first choice */
2044   {
2045 #ifdef HAVE_MONOTONIC_CLOCK
2046     static volatile gsize clockid = 0;
2047 #else
2048     static clockid_t clockid = CLOCK_REALTIME;
2049 #endif
2050     struct timespec ts;
2051
2052 #ifdef HAVE_MONOTONIC_CLOCK
2053     if (g_once_init_enter (&clockid))
2054       {
2055         clockid_t best_clockid;
2056
2057         if (sysconf (_SC_MONOTONIC_CLOCK) >= 0)
2058           best_clockid = CLOCK_MONOTONIC;
2059         else
2060           best_clockid = CLOCK_REALTIME;
2061         g_once_init_leave (&clockid, (gsize)best_clockid);
2062       }
2063 #endif
2064
2065     clock_gettime (clockid, &ts);
2066
2067     /* In theory monotonic time can have any epoch.
2068      *
2069      * glib presently assumes the following:
2070      *
2071      *   1) The epoch comes some time after the birth of Jesus of Nazareth, but
2072      *      not more than 10000 years later.
2073      *
2074      *   2) The current time also falls sometime within this range.
2075      *
2076      * These two reasonable assumptions leave us with a maximum deviation from
2077      * the epoch of 10000 years, or 315569520000000000 seconds.
2078      *
2079      * If we restrict ourselves to this range then the number of microseconds
2080      * will always fit well inside the constraints of a int64 (by a factor of
2081      * about 29).
2082      *
2083      * If you actually hit the following assertion, probably you should file a
2084      * bug against your operating system for being excessively silly.
2085      **/
2086     g_assert (G_GINT64_CONSTANT (-315569520000000000) < ts.tv_sec &&
2087               ts.tv_sec < G_GINT64_CONSTANT (315569520000000000));
2088
2089     return (((gint64) ts.tv_sec) * 1000000) + (ts.tv_nsec / 1000);
2090   }
2091 #else
2092   /* It may look like we are discarding accuracy on Windows (since its
2093    * current time is expressed in 100s of nanoseconds) but according to
2094    * many sources, the time is only updated 64 times per second, so
2095    * microsecond accuracy is more than enough.
2096    */
2097   {
2098     GTimeVal tv;
2099
2100     g_get_current_time (&tv);
2101
2102     return (((gint64) tv.tv_sec) * 1000000) + tv.tv_usec;
2103   }
2104 #endif
2105 }
2106
2107 static void
2108 g_main_dispatch_free (gpointer dispatch)
2109 {
2110   g_slice_free (GMainDispatch, dispatch);
2111 }
2112
2113 /* Running the main loop */
2114
2115 static GMainDispatch *
2116 get_dispatch (void)
2117 {
2118   static GStaticPrivate depth_private = G_STATIC_PRIVATE_INIT;
2119   GMainDispatch *dispatch = g_static_private_get (&depth_private);
2120   if (!dispatch)
2121     {
2122       dispatch = g_slice_new0 (GMainDispatch);
2123       g_static_private_set (&depth_private, dispatch, g_main_dispatch_free);
2124     }
2125
2126   return dispatch;
2127 }
2128
2129 /**
2130  * g_main_depth:
2131  *
2132  * Returns the depth of the stack of calls to
2133  * g_main_context_dispatch() on any #GMainContext in the current thread.
2134  *  That is, when called from the toplevel, it gives 0. When
2135  * called from within a callback from g_main_context_iteration()
2136  * (or g_main_loop_run(), etc.) it returns 1. When called from within 
2137  * a callback to a recursive call to g_main_context_iteration(),
2138  * it returns 2. And so forth.
2139  *
2140  * This function is useful in a situation like the following:
2141  * Imagine an extremely simple "garbage collected" system.
2142  *
2143  * |[
2144  * static GList *free_list;
2145  * 
2146  * gpointer
2147  * allocate_memory (gsize size)
2148  * { 
2149  *   gpointer result = g_malloc (size);
2150  *   free_list = g_list_prepend (free_list, result);
2151  *   return result;
2152  * }
2153  * 
2154  * void
2155  * free_allocated_memory (void)
2156  * {
2157  *   GList *l;
2158  *   for (l = free_list; l; l = l->next);
2159  *     g_free (l->data);
2160  *   g_list_free (free_list);
2161  *   free_list = NULL;
2162  *  }
2163  * 
2164  * [...]
2165  * 
2166  * while (TRUE); 
2167  *  {
2168  *    g_main_context_iteration (NULL, TRUE);
2169  *    free_allocated_memory();
2170  *   }
2171  * ]|
2172  *
2173  * This works from an application, however, if you want to do the same
2174  * thing from a library, it gets more difficult, since you no longer
2175  * control the main loop. You might think you can simply use an idle
2176  * function to make the call to free_allocated_memory(), but that
2177  * doesn't work, since the idle function could be called from a
2178  * recursive callback. This can be fixed by using g_main_depth()
2179  *
2180  * |[
2181  * gpointer
2182  * allocate_memory (gsize size)
2183  * { 
2184  *   FreeListBlock *block = g_new (FreeListBlock, 1);
2185  *   block->mem = g_malloc (size);
2186  *   block->depth = g_main_depth ();   
2187  *   free_list = g_list_prepend (free_list, block);
2188  *   return block->mem;
2189  * }
2190  * 
2191  * void
2192  * free_allocated_memory (void)
2193  * {
2194  *   GList *l;
2195  *   
2196  *   int depth = g_main_depth ();
2197  *   for (l = free_list; l; );
2198  *     {
2199  *       GList *next = l->next;
2200  *       FreeListBlock *block = l->data;
2201  *       if (block->depth > depth)
2202  *         {
2203  *           g_free (block->mem);
2204  *           g_free (block);
2205  *           free_list = g_list_delete_link (free_list, l);
2206  *         }
2207  *               
2208  *       l = next;
2209  *     }
2210  *   }
2211  * ]|
2212  *
2213  * There is a temptation to use g_main_depth() to solve
2214  * problems with reentrancy. For instance, while waiting for data
2215  * to be received from the network in response to a menu item,
2216  * the menu item might be selected again. It might seem that
2217  * one could make the menu item's callback return immediately
2218  * and do nothing if g_main_depth() returns a value greater than 1.
2219  * However, this should be avoided since the user then sees selecting
2220  * the menu item do nothing. Furthermore, you'll find yourself adding
2221  * these checks all over your code, since there are doubtless many,
2222  * many things that the user could do. Instead, you can use the
2223  * following techniques:
2224  *
2225  * <orderedlist>
2226  *  <listitem>
2227  *   <para>
2228  *     Use gtk_widget_set_sensitive() or modal dialogs to prevent
2229  *     the user from interacting with elements while the main
2230  *     loop is recursing.
2231  *   </para>
2232  *  </listitem>
2233  *  <listitem>
2234  *   <para>
2235  *     Avoid main loop recursion in situations where you can't handle
2236  *     arbitrary  callbacks. Instead, structure your code so that you
2237  *     simply return to the main loop and then get called again when
2238  *     there is more work to do.
2239  *   </para>
2240  *  </listitem>
2241  * </orderedlist>
2242  * 
2243  * Return value: The main loop recursion level in the current thread
2244  **/
2245 int
2246 g_main_depth (void)
2247 {
2248   GMainDispatch *dispatch = get_dispatch ();
2249   return dispatch->depth;
2250 }
2251
2252 /**
2253  * g_main_current_source:
2254  *
2255  * Returns the currently firing source for this thread.
2256  * 
2257  * Return value: The currently firing source or %NULL.
2258  *
2259  * Since: 2.12
2260  */
2261 GSource *
2262 g_main_current_source (void)
2263 {
2264   GMainDispatch *dispatch = get_dispatch ();
2265   return dispatch->dispatching_sources ? dispatch->dispatching_sources->data : NULL;
2266 }
2267
2268 /**
2269  * g_source_is_destroyed:
2270  * @source: a #GSource
2271  *
2272  * Returns whether @source has been destroyed.
2273  *
2274  * This is important when you operate upon your objects 
2275  * from within idle handlers, but may have freed the object 
2276  * before the dispatch of your idle handler.
2277  *
2278  * |[
2279  * static gboolean 
2280  * idle_callback (gpointer data)
2281  * {
2282  *   SomeWidget *self = data;
2283  *    
2284  *   GDK_THREADS_ENTER (<!-- -->);
2285  *   /<!-- -->* do stuff with self *<!-- -->/
2286  *   self->idle_id = 0;
2287  *   GDK_THREADS_LEAVE (<!-- -->);
2288  *    
2289  *   return FALSE;
2290  * }
2291  *  
2292  * static void 
2293  * some_widget_do_stuff_later (SomeWidget *self)
2294  * {
2295  *   self->idle_id = g_idle_add (idle_callback, self);
2296  * }
2297  *  
2298  * static void 
2299  * some_widget_finalize (GObject *object)
2300  * {
2301  *   SomeWidget *self = SOME_WIDGET (object);
2302  *    
2303  *   if (self->idle_id)
2304  *     g_source_remove (self->idle_id);
2305  *    
2306  *   G_OBJECT_CLASS (parent_class)->finalize (object);
2307  * }
2308  * ]|
2309  *
2310  * This will fail in a multi-threaded application if the 
2311  * widget is destroyed before the idle handler fires due 
2312  * to the use after free in the callback. A solution, to 
2313  * this particular problem, is to check to if the source
2314  * has already been destroy within the callback.
2315  *
2316  * |[
2317  * static gboolean 
2318  * idle_callback (gpointer data)
2319  * {
2320  *   SomeWidget *self = data;
2321  *   
2322  *   GDK_THREADS_ENTER ();
2323  *   if (!g_source_is_destroyed (g_main_current_source ()))
2324  *     {
2325  *       /<!-- -->* do stuff with self *<!-- -->/
2326  *     }
2327  *   GDK_THREADS_LEAVE ();
2328  *   
2329  *   return FALSE;
2330  * }
2331  * ]|
2332  *
2333  * Return value: %TRUE if the source has been destroyed
2334  *
2335  * Since: 2.12
2336  */
2337 gboolean
2338 g_source_is_destroyed (GSource *source)
2339 {
2340   return SOURCE_DESTROYED (source);
2341 }
2342
2343 /* Temporarily remove all this source's file descriptors from the
2344  * poll(), so that if data comes available for one of the file descriptors
2345  * we don't continually spin in the poll()
2346  */
2347 /* HOLDS: source->context's lock */
2348 static void
2349 block_source (GSource *source)
2350 {
2351   GSList *tmp_list;
2352
2353   g_return_if_fail (!SOURCE_BLOCKED (source));
2354
2355   tmp_list = source->poll_fds;
2356   while (tmp_list)
2357     {
2358       g_main_context_remove_poll_unlocked (source->context, tmp_list->data);
2359       tmp_list = tmp_list->next;
2360     }
2361 }
2362
2363 /* HOLDS: source->context's lock */
2364 static void
2365 unblock_source (GSource *source)
2366 {
2367   GSList *tmp_list;
2368   
2369   g_return_if_fail (!SOURCE_BLOCKED (source)); /* Source already unblocked */
2370   g_return_if_fail (!SOURCE_DESTROYED (source));
2371   
2372   tmp_list = source->poll_fds;
2373   while (tmp_list)
2374     {
2375       g_main_context_add_poll_unlocked (source->context, source->priority, tmp_list->data);
2376       tmp_list = tmp_list->next;
2377     }
2378 }
2379
2380 /* HOLDS: context's lock */
2381 static void
2382 g_main_dispatch (GMainContext *context)
2383 {
2384   GMainDispatch *current = get_dispatch ();
2385   guint i;
2386
2387   for (i = 0; i < context->pending_dispatches->len; i++)
2388     {
2389       GSource *source = context->pending_dispatches->pdata[i];
2390
2391       context->pending_dispatches->pdata[i] = NULL;
2392       g_assert (source);
2393
2394       source->flags &= ~G_SOURCE_READY;
2395
2396       if (!SOURCE_DESTROYED (source))
2397         {
2398           gboolean was_in_call;
2399           gpointer user_data = NULL;
2400           GSourceFunc callback = NULL;
2401           GSourceCallbackFuncs *cb_funcs;
2402           gpointer cb_data;
2403           gboolean need_destroy;
2404
2405           gboolean (*dispatch) (GSource *,
2406                                 GSourceFunc,
2407                                 gpointer);
2408           GSList current_source_link;
2409
2410           dispatch = source->source_funcs->dispatch;
2411           cb_funcs = source->callback_funcs;
2412           cb_data = source->callback_data;
2413
2414           if (cb_funcs)
2415             cb_funcs->ref (cb_data);
2416           
2417           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0)
2418             block_source (source);
2419           
2420           was_in_call = source->flags & G_HOOK_FLAG_IN_CALL;
2421           source->flags |= G_HOOK_FLAG_IN_CALL;
2422
2423           if (cb_funcs)
2424             cb_funcs->get (cb_data, source, &callback, &user_data);
2425
2426           UNLOCK_CONTEXT (context);
2427
2428           current->depth++;
2429           /* The on-stack allocation of the GSList is unconventional, but
2430            * we know that the lifetime of the link is bounded to this
2431            * function as the link is kept in a thread specific list and
2432            * not manipulated outside of this function and its descendants.
2433            * Avoiding the overhead of a g_slist_alloc() is useful as many
2434            * applications do little more than dispatch events.
2435            *
2436            * This is a performance hack - do not revert to g_slist_prepend()!
2437            */
2438           current_source_link.data = source;
2439           current_source_link.next = current->dispatching_sources;
2440           current->dispatching_sources = &current_source_link;
2441           need_destroy = ! dispatch (source,
2442                                      callback,
2443                                      user_data);
2444           g_assert (current->dispatching_sources == &current_source_link);
2445           current->dispatching_sources = current_source_link.next;
2446           current->depth--;
2447           
2448           if (cb_funcs)
2449             cb_funcs->unref (cb_data);
2450
2451           LOCK_CONTEXT (context);
2452           
2453           if (!was_in_call)
2454             source->flags &= ~G_HOOK_FLAG_IN_CALL;
2455
2456           if ((source->flags & G_SOURCE_CAN_RECURSE) == 0 &&
2457               !SOURCE_DESTROYED (source))
2458             unblock_source (source);
2459           
2460           /* Note: this depends on the fact that we can't switch
2461            * sources from one main context to another
2462            */
2463           if (need_destroy && !SOURCE_DESTROYED (source))
2464             {
2465               g_assert (source->context == context);
2466               g_source_destroy_internal (source, context, TRUE);
2467             }
2468         }
2469       
2470       SOURCE_UNREF (source, context);
2471     }
2472
2473   g_ptr_array_set_size (context->pending_dispatches, 0);
2474 }
2475
2476 /* Holds context's lock */
2477 static inline GSource *
2478 next_valid_source (GMainContext *context,
2479                    GSource      *source)
2480 {
2481   GSource *new_source = source ? source->next : context->source_list;
2482
2483   while (new_source)
2484     {
2485       if (!SOURCE_DESTROYED (new_source))
2486         {
2487           new_source->ref_count++;
2488           break;
2489         }
2490       
2491       new_source = new_source->next;
2492     }
2493
2494   if (source)
2495     SOURCE_UNREF (source, context);
2496           
2497   return new_source;
2498 }
2499
2500 /**
2501  * g_main_context_acquire:
2502  * @context: a #GMainContext
2503  * 
2504  * Tries to become the owner of the specified context.
2505  * If some other thread is the owner of the context,
2506  * returns %FALSE immediately. Ownership is properly
2507  * recursive: the owner can require ownership again
2508  * and will release ownership when g_main_context_release()
2509  * is called as many times as g_main_context_acquire().
2510  *
2511  * You must be the owner of a context before you
2512  * can call g_main_context_prepare(), g_main_context_query(),
2513  * g_main_context_check(), g_main_context_dispatch().
2514  * 
2515  * Return value: %TRUE if the operation succeeded, and
2516  *   this thread is now the owner of @context.
2517  **/
2518 gboolean 
2519 g_main_context_acquire (GMainContext *context)
2520 {
2521 #ifdef G_THREADS_ENABLED
2522   gboolean result = FALSE;
2523   GThread *self = G_THREAD_SELF;
2524
2525   if (context == NULL)
2526     context = g_main_context_default ();
2527   
2528   LOCK_CONTEXT (context);
2529
2530   if (!context->owner)
2531     {
2532       context->owner = self;
2533       g_assert (context->owner_count == 0);
2534     }
2535
2536   if (context->owner == self)
2537     {
2538       context->owner_count++;
2539       result = TRUE;
2540     }
2541
2542   UNLOCK_CONTEXT (context); 
2543   
2544   return result;
2545 #else /* !G_THREADS_ENABLED */
2546   return TRUE;
2547 #endif /* G_THREADS_ENABLED */
2548 }
2549
2550 /**
2551  * g_main_context_release:
2552  * @context: a #GMainContext
2553  * 
2554  * Releases ownership of a context previously acquired by this thread
2555  * with g_main_context_acquire(). If the context was acquired multiple
2556  * times, the ownership will be released only when g_main_context_release()
2557  * is called as many times as it was acquired.
2558  **/
2559 void
2560 g_main_context_release (GMainContext *context)
2561 {
2562 #ifdef G_THREADS_ENABLED
2563   if (context == NULL)
2564     context = g_main_context_default ();
2565   
2566   LOCK_CONTEXT (context);
2567
2568   context->owner_count--;
2569   if (context->owner_count == 0)
2570     {
2571       context->owner = NULL;
2572
2573       if (context->waiters)
2574         {
2575           GMainWaiter *waiter = context->waiters->data;
2576           gboolean loop_internal_waiter =
2577             (waiter->mutex == g_static_mutex_get_mutex (&context->mutex));
2578           context->waiters = g_slist_delete_link (context->waiters,
2579                                                   context->waiters);
2580           if (!loop_internal_waiter)
2581             g_mutex_lock (waiter->mutex);
2582           
2583           g_cond_signal (waiter->cond);
2584           
2585           if (!loop_internal_waiter)
2586             g_mutex_unlock (waiter->mutex);
2587         }
2588     }
2589
2590   UNLOCK_CONTEXT (context); 
2591 #endif /* G_THREADS_ENABLED */
2592 }
2593
2594 /**
2595  * g_main_context_wait:
2596  * @context: a #GMainContext
2597  * @cond: a condition variable
2598  * @mutex: a mutex, currently held
2599  * 
2600  * Tries to become the owner of the specified context,
2601  * as with g_main_context_acquire(). But if another thread
2602  * is the owner, atomically drop @mutex and wait on @cond until 
2603  * that owner releases ownership or until @cond is signaled, then
2604  * try again (once) to become the owner.
2605  * 
2606  * Return value: %TRUE if the operation succeeded, and
2607  *   this thread is now the owner of @context.
2608  **/
2609 gboolean
2610 g_main_context_wait (GMainContext *context,
2611                      GCond        *cond,
2612                      GMutex       *mutex)
2613 {
2614 #ifdef G_THREADS_ENABLED
2615   gboolean result = FALSE;
2616   GThread *self = G_THREAD_SELF;
2617   gboolean loop_internal_waiter;
2618   
2619   if (context == NULL)
2620     context = g_main_context_default ();
2621
2622   loop_internal_waiter = (mutex == g_static_mutex_get_mutex (&context->mutex));
2623   
2624   if (!loop_internal_waiter)
2625     LOCK_CONTEXT (context);
2626
2627   if (context->owner && context->owner != self)
2628     {
2629       GMainWaiter waiter;
2630
2631       waiter.cond = cond;
2632       waiter.mutex = mutex;
2633
2634       context->waiters = g_slist_append (context->waiters, &waiter);
2635       
2636       if (!loop_internal_waiter)
2637         UNLOCK_CONTEXT (context);
2638       g_cond_wait (cond, mutex);
2639       if (!loop_internal_waiter)      
2640         LOCK_CONTEXT (context);
2641
2642       context->waiters = g_slist_remove (context->waiters, &waiter);
2643     }
2644
2645   if (!context->owner)
2646     {
2647       context->owner = self;
2648       g_assert (context->owner_count == 0);
2649     }
2650
2651   if (context->owner == self)
2652     {
2653       context->owner_count++;
2654       result = TRUE;
2655     }
2656
2657   if (!loop_internal_waiter)
2658     UNLOCK_CONTEXT (context); 
2659   
2660   return result;
2661 #else /* !G_THREADS_ENABLED */
2662   return TRUE;
2663 #endif /* G_THREADS_ENABLED */
2664 }
2665
2666 /**
2667  * g_main_context_prepare:
2668  * @context: a #GMainContext
2669  * @priority: location to store priority of highest priority
2670  *            source already ready.
2671  * 
2672  * Prepares to poll sources within a main loop. The resulting information
2673  * for polling is determined by calling g_main_context_query ().
2674  * 
2675  * Return value: %TRUE if some source is ready to be dispatched
2676  *               prior to polling.
2677  **/
2678 gboolean
2679 g_main_context_prepare (GMainContext *context,
2680                         gint         *priority)
2681 {
2682   gint i;
2683   gint n_ready = 0;
2684   gint current_priority = G_MAXINT;
2685   GSource *source;
2686
2687   if (context == NULL)
2688     context = g_main_context_default ();
2689   
2690   LOCK_CONTEXT (context);
2691
2692   context->time_is_fresh = FALSE;
2693   context->real_time_is_fresh = FALSE;
2694
2695   if (context->in_check_or_prepare)
2696     {
2697       g_warning ("g_main_context_prepare() called recursively from within a source's check() or "
2698                  "prepare() member.");
2699       UNLOCK_CONTEXT (context);
2700       return FALSE;
2701     }
2702
2703 #ifdef G_THREADS_ENABLED
2704   if (context->poll_waiting)
2705     {
2706       g_warning("g_main_context_prepare(): main loop already active in another thread");
2707       UNLOCK_CONTEXT (context);
2708       return FALSE;
2709     }
2710   
2711   context->poll_waiting = TRUE;
2712 #endif /* G_THREADS_ENABLED */
2713
2714 #if 0
2715   /* If recursing, finish up current dispatch, before starting over */
2716   if (context->pending_dispatches)
2717     {
2718       if (dispatch)
2719         g_main_dispatch (context, &current_time);
2720       
2721       UNLOCK_CONTEXT (context);
2722       return TRUE;
2723     }
2724 #endif
2725
2726   /* If recursing, clear list of pending dispatches */
2727
2728   for (i = 0; i < context->pending_dispatches->len; i++)
2729     {
2730       if (context->pending_dispatches->pdata[i])
2731         SOURCE_UNREF ((GSource *)context->pending_dispatches->pdata[i], context);
2732     }
2733   g_ptr_array_set_size (context->pending_dispatches, 0);
2734   
2735   /* Prepare all sources */
2736
2737   context->timeout = -1;
2738   
2739   source = next_valid_source (context, NULL);
2740   while (source)
2741     {
2742       gint source_timeout = -1;
2743
2744       if ((n_ready > 0) && (source->priority > current_priority))
2745         {
2746           SOURCE_UNREF (source, context);
2747           break;
2748         }
2749       if (SOURCE_BLOCKED (source))
2750         goto next;
2751
2752       if (!(source->flags & G_SOURCE_READY))
2753         {
2754           gboolean result;
2755           gboolean (*prepare)  (GSource  *source, 
2756                                 gint     *timeout);
2757
2758           prepare = source->source_funcs->prepare;
2759           context->in_check_or_prepare++;
2760           UNLOCK_CONTEXT (context);
2761
2762           result = (*prepare) (source, &source_timeout);
2763
2764           LOCK_CONTEXT (context);
2765           context->in_check_or_prepare--;
2766
2767           if (result)
2768             {
2769               GSource *ready_source = source;
2770
2771               while (ready_source)
2772                 {
2773                   ready_source->flags |= G_SOURCE_READY;
2774                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2775                 }
2776             }
2777         }
2778
2779       if (source->flags & G_SOURCE_READY)
2780         {
2781           n_ready++;
2782           current_priority = source->priority;
2783           context->timeout = 0;
2784         }
2785       
2786       if (source_timeout >= 0)
2787         {
2788           if (context->timeout < 0)
2789             context->timeout = source_timeout;
2790           else
2791             context->timeout = MIN (context->timeout, source_timeout);
2792         }
2793
2794     next:
2795       source = next_valid_source (context, source);
2796     }
2797
2798   UNLOCK_CONTEXT (context);
2799   
2800   if (priority)
2801     *priority = current_priority;
2802   
2803   return (n_ready > 0);
2804 }
2805
2806 /**
2807  * g_main_context_query:
2808  * @context: a #GMainContext
2809  * @max_priority: maximum priority source to check
2810  * @timeout_: location to store timeout to be used in polling
2811  * @fds: location to store #GPollFD records that need to be polled.
2812  * @n_fds: length of @fds.
2813  * 
2814  * Determines information necessary to poll this main loop.
2815  * 
2816  * Return value: the number of records actually stored in @fds,
2817  *   or, if more than @n_fds records need to be stored, the number
2818  *   of records that need to be stored.
2819  **/
2820 gint
2821 g_main_context_query (GMainContext *context,
2822                       gint          max_priority,
2823                       gint         *timeout,
2824                       GPollFD      *fds,
2825                       gint          n_fds)
2826 {
2827   gint n_poll;
2828   GPollRec *pollrec;
2829   
2830   LOCK_CONTEXT (context);
2831
2832   pollrec = context->poll_records;
2833   n_poll = 0;
2834   while (pollrec && max_priority >= pollrec->priority)
2835     {
2836       /* We need to include entries with fd->events == 0 in the array because
2837        * otherwise if the application changes fd->events behind our back and 
2838        * makes it non-zero, we'll be out of sync when we check the fds[] array.
2839        * (Changing fd->events after adding an FD wasn't an anticipated use of 
2840        * this API, but it occurs in practice.) */
2841       if (n_poll < n_fds)
2842         {
2843           fds[n_poll].fd = pollrec->fd->fd;
2844           /* In direct contradiction to the Unix98 spec, IRIX runs into
2845            * difficulty if you pass in POLLERR, POLLHUP or POLLNVAL
2846            * flags in the events field of the pollfd while it should
2847            * just ignoring them. So we mask them out here.
2848            */
2849           fds[n_poll].events = pollrec->fd->events & ~(G_IO_ERR|G_IO_HUP|G_IO_NVAL);
2850           fds[n_poll].revents = 0;
2851         }
2852
2853       pollrec = pollrec->next;
2854       n_poll++;
2855     }
2856
2857 #ifdef G_THREADS_ENABLED
2858   context->poll_changed = FALSE;
2859 #endif
2860   
2861   if (timeout)
2862     {
2863       *timeout = context->timeout;
2864       if (*timeout != 0)
2865         {
2866           context->time_is_fresh = FALSE;
2867           context->real_time_is_fresh = FALSE;
2868         }
2869     }
2870   
2871   UNLOCK_CONTEXT (context);
2872
2873   return n_poll;
2874 }
2875
2876 /**
2877  * g_main_context_check:
2878  * @context: a #GMainContext
2879  * @max_priority: the maximum numerical priority of sources to check
2880  * @fds: array of #GPollFD's that was passed to the last call to
2881  *       g_main_context_query()
2882  * @n_fds: return value of g_main_context_query()
2883  * 
2884  * Passes the results of polling back to the main loop.
2885  * 
2886  * Return value: %TRUE if some sources are ready to be dispatched.
2887  **/
2888 gboolean
2889 g_main_context_check (GMainContext *context,
2890                       gint          max_priority,
2891                       GPollFD      *fds,
2892                       gint          n_fds)
2893 {
2894   GSource *source;
2895   GPollRec *pollrec;
2896   gint n_ready = 0;
2897   gint i;
2898    
2899   LOCK_CONTEXT (context);
2900
2901   if (context->in_check_or_prepare)
2902     {
2903       g_warning ("g_main_context_check() called recursively from within a source's check() or "
2904                  "prepare() member.");
2905       UNLOCK_CONTEXT (context);
2906       return FALSE;
2907     }
2908   
2909 #ifdef G_THREADS_ENABLED
2910   if (!context->poll_waiting)
2911     g_wakeup_acknowledge (context->wakeup);
2912
2913   else
2914     context->poll_waiting = FALSE;
2915
2916   /* If the set of poll file descriptors changed, bail out
2917    * and let the main loop rerun
2918    */
2919   if (context->poll_changed)
2920     {
2921       UNLOCK_CONTEXT (context);
2922       return FALSE;
2923     }
2924 #endif /* G_THREADS_ENABLED */
2925   
2926   pollrec = context->poll_records;
2927   i = 0;
2928   while (i < n_fds)
2929     {
2930       if (pollrec->fd->events)
2931         pollrec->fd->revents = fds[i].revents;
2932
2933       pollrec = pollrec->next;
2934       i++;
2935     }
2936
2937   source = next_valid_source (context, NULL);
2938   while (source)
2939     {
2940       if ((n_ready > 0) && (source->priority > max_priority))
2941         {
2942           SOURCE_UNREF (source, context);
2943           break;
2944         }
2945       if (SOURCE_BLOCKED (source))
2946         goto next;
2947
2948       if (!(source->flags & G_SOURCE_READY))
2949         {
2950           gboolean result;
2951           gboolean (*check) (GSource  *source);
2952
2953           check = source->source_funcs->check;
2954           
2955           context->in_check_or_prepare++;
2956           UNLOCK_CONTEXT (context);
2957           
2958           result = (*check) (source);
2959           
2960           LOCK_CONTEXT (context);
2961           context->in_check_or_prepare--;
2962           
2963           if (result)
2964             {
2965               GSource *ready_source = source;
2966
2967               while (ready_source)
2968                 {
2969                   ready_source->flags |= G_SOURCE_READY;
2970                   ready_source = ready_source->priv ? ready_source->priv->parent_source : NULL;
2971                 }
2972             }
2973         }
2974
2975       if (source->flags & G_SOURCE_READY)
2976         {
2977           source->ref_count++;
2978           g_ptr_array_add (context->pending_dispatches, source);
2979
2980           n_ready++;
2981
2982           /* never dispatch sources with less priority than the first
2983            * one we choose to dispatch
2984            */
2985           max_priority = source->priority;
2986         }
2987
2988     next:
2989       source = next_valid_source (context, source);
2990     }
2991
2992   UNLOCK_CONTEXT (context);
2993
2994   return n_ready > 0;
2995 }
2996
2997 /**
2998  * g_main_context_dispatch:
2999  * @context: a #GMainContext
3000  * 
3001  * Dispatches all pending sources.
3002  **/
3003 void
3004 g_main_context_dispatch (GMainContext *context)
3005 {
3006   LOCK_CONTEXT (context);
3007
3008   if (context->pending_dispatches->len > 0)
3009     {
3010       g_main_dispatch (context);
3011     }
3012
3013   UNLOCK_CONTEXT (context);
3014 }
3015
3016 /* HOLDS context lock */
3017 static gboolean
3018 g_main_context_iterate (GMainContext *context,
3019                         gboolean      block,
3020                         gboolean      dispatch,
3021                         GThread      *self)
3022 {
3023   gint max_priority;
3024   gint timeout;
3025   gboolean some_ready;
3026   gint nfds, allocated_nfds;
3027   GPollFD *fds = NULL;
3028
3029   UNLOCK_CONTEXT (context);
3030
3031 #ifdef G_THREADS_ENABLED
3032   if (!g_main_context_acquire (context))
3033     {
3034       gboolean got_ownership;
3035
3036       LOCK_CONTEXT (context);
3037
3038       g_return_val_if_fail (g_thread_supported (), FALSE);
3039
3040       if (!block)
3041         return FALSE;
3042
3043       if (!context->cond)
3044         context->cond = g_cond_new ();
3045
3046       got_ownership = g_main_context_wait (context,
3047                                            context->cond,
3048                                            g_static_mutex_get_mutex (&context->mutex));
3049
3050       if (!got_ownership)
3051         return FALSE;
3052     }
3053   else
3054     LOCK_CONTEXT (context);
3055 #endif /* G_THREADS_ENABLED */
3056   
3057   if (!context->cached_poll_array)
3058     {
3059       context->cached_poll_array_size = context->n_poll_records;
3060       context->cached_poll_array = g_new (GPollFD, context->n_poll_records);
3061     }
3062
3063   allocated_nfds = context->cached_poll_array_size;
3064   fds = context->cached_poll_array;
3065   
3066   UNLOCK_CONTEXT (context);
3067
3068   g_main_context_prepare (context, &max_priority); 
3069   
3070   while ((nfds = g_main_context_query (context, max_priority, &timeout, fds, 
3071                                        allocated_nfds)) > allocated_nfds)
3072     {
3073       LOCK_CONTEXT (context);
3074       g_free (fds);
3075       context->cached_poll_array_size = allocated_nfds = nfds;
3076       context->cached_poll_array = fds = g_new (GPollFD, nfds);
3077       UNLOCK_CONTEXT (context);
3078     }
3079
3080   if (!block)
3081     timeout = 0;
3082   
3083   g_main_context_poll (context, timeout, max_priority, fds, nfds);
3084   
3085   some_ready = g_main_context_check (context, max_priority, fds, nfds);
3086   
3087   if (dispatch)
3088     g_main_context_dispatch (context);
3089   
3090 #ifdef G_THREADS_ENABLED
3091   g_main_context_release (context);
3092 #endif /* G_THREADS_ENABLED */    
3093
3094   LOCK_CONTEXT (context);
3095
3096   return some_ready;
3097 }
3098
3099 /**
3100  * g_main_context_pending:
3101  * @context: a #GMainContext (if %NULL, the default context will be used)
3102  *
3103  * Checks if any sources have pending events for the given context.
3104  * 
3105  * Return value: %TRUE if events are pending.
3106  **/
3107 gboolean 
3108 g_main_context_pending (GMainContext *context)
3109 {
3110   gboolean retval;
3111
3112   if (!context)
3113     context = g_main_context_default();
3114
3115   LOCK_CONTEXT (context);
3116   retval = g_main_context_iterate (context, FALSE, FALSE, G_THREAD_SELF);
3117   UNLOCK_CONTEXT (context);
3118   
3119   return retval;
3120 }
3121
3122 /**
3123  * g_main_context_iteration:
3124  * @context: a #GMainContext (if %NULL, the default context will be used) 
3125  * @may_block: whether the call may block.
3126  * 
3127  * Runs a single iteration for the given main loop. This involves
3128  * checking to see if any event sources are ready to be processed,
3129  * then if no events sources are ready and @may_block is %TRUE, waiting
3130  * for a source to become ready, then dispatching the highest priority
3131  * events sources that are ready. Otherwise, if @may_block is %FALSE 
3132  * sources are not waited to become ready, only those highest priority 
3133  * events sources will be dispatched (if any), that are ready at this 
3134  * given moment without further waiting.
3135  *
3136  * Note that even when @may_block is %TRUE, it is still possible for 
3137  * g_main_context_iteration() to return %FALSE, since the the wait may 
3138  * be interrupted for other reasons than an event source becoming ready.
3139  * 
3140  * Return value: %TRUE if events were dispatched.
3141  **/
3142 gboolean
3143 g_main_context_iteration (GMainContext *context, gboolean may_block)
3144 {
3145   gboolean retval;
3146
3147   if (!context)
3148     context = g_main_context_default();
3149   
3150   LOCK_CONTEXT (context);
3151   retval = g_main_context_iterate (context, may_block, TRUE, G_THREAD_SELF);
3152   UNLOCK_CONTEXT (context);
3153   
3154   return retval;
3155 }
3156
3157 /**
3158  * g_main_loop_new:
3159  * @context: (allow-none): a #GMainContext  (if %NULL, the default context will be used).
3160  * @is_running: set to %TRUE to indicate that the loop is running. This
3161  * is not very important since calling g_main_loop_run() will set this to
3162  * %TRUE anyway.
3163  * 
3164  * Creates a new #GMainLoop structure.
3165  * 
3166  * Return value: a new #GMainLoop.
3167  **/
3168 GMainLoop *
3169 g_main_loop_new (GMainContext *context,
3170                  gboolean      is_running)
3171 {
3172   GMainLoop *loop;
3173
3174   if (!context)
3175     context = g_main_context_default();
3176   
3177   g_main_context_ref (context);
3178
3179   loop = g_new0 (GMainLoop, 1);
3180   loop->context = context;
3181   loop->is_running = is_running != FALSE;
3182   loop->ref_count = 1;
3183   
3184   return loop;
3185 }
3186
3187 /**
3188  * g_main_loop_ref:
3189  * @loop: a #GMainLoop
3190  * 
3191  * Increases the reference count on a #GMainLoop object by one.
3192  * 
3193  * Return value: @loop
3194  **/
3195 GMainLoop *
3196 g_main_loop_ref (GMainLoop *loop)
3197 {
3198   g_return_val_if_fail (loop != NULL, NULL);
3199   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3200
3201   g_atomic_int_inc (&loop->ref_count);
3202
3203   return loop;
3204 }
3205
3206 /**
3207  * g_main_loop_unref:
3208  * @loop: a #GMainLoop
3209  * 
3210  * Decreases the reference count on a #GMainLoop object by one. If
3211  * the result is zero, free the loop and free all associated memory.
3212  **/
3213 void
3214 g_main_loop_unref (GMainLoop *loop)
3215 {
3216   g_return_if_fail (loop != NULL);
3217   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3218
3219   if (!g_atomic_int_dec_and_test (&loop->ref_count))
3220     return;
3221
3222   g_main_context_unref (loop->context);
3223   g_free (loop);
3224 }
3225
3226 /**
3227  * g_main_loop_run:
3228  * @loop: a #GMainLoop
3229  * 
3230  * Runs a main loop until g_main_loop_quit() is called on the loop.
3231  * If this is called for the thread of the loop's #GMainContext,
3232  * it will process events from the loop, otherwise it will
3233  * simply wait.
3234  **/
3235 void 
3236 g_main_loop_run (GMainLoop *loop)
3237 {
3238   GThread *self = G_THREAD_SELF;
3239
3240   g_return_if_fail (loop != NULL);
3241   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3242
3243 #ifdef G_THREADS_ENABLED
3244   if (!g_main_context_acquire (loop->context))
3245     {
3246       gboolean got_ownership = FALSE;
3247       
3248       /* Another thread owns this context */
3249       if (!g_thread_supported ())
3250         {
3251           g_warning ("g_main_loop_run() was called from second thread but "
3252                      "g_thread_init() was never called.");
3253           return;
3254         }
3255       
3256       LOCK_CONTEXT (loop->context);
3257
3258       g_atomic_int_inc (&loop->ref_count);
3259
3260       if (!loop->is_running)
3261         loop->is_running = TRUE;
3262
3263       if (!loop->context->cond)
3264         loop->context->cond = g_cond_new ();
3265           
3266       while (loop->is_running && !got_ownership)
3267         got_ownership = g_main_context_wait (loop->context,
3268                                              loop->context->cond,
3269                                              g_static_mutex_get_mutex (&loop->context->mutex));
3270       
3271       if (!loop->is_running)
3272         {
3273           UNLOCK_CONTEXT (loop->context);
3274           if (got_ownership)
3275             g_main_context_release (loop->context);
3276           g_main_loop_unref (loop);
3277           return;
3278         }
3279
3280       g_assert (got_ownership);
3281     }
3282   else
3283     LOCK_CONTEXT (loop->context);
3284 #endif /* G_THREADS_ENABLED */ 
3285
3286   if (loop->context->in_check_or_prepare)
3287     {
3288       g_warning ("g_main_loop_run(): called recursively from within a source's "
3289                  "check() or prepare() member, iteration not possible.");
3290       return;
3291     }
3292
3293   g_atomic_int_inc (&loop->ref_count);
3294   loop->is_running = TRUE;
3295   while (loop->is_running)
3296     g_main_context_iterate (loop->context, TRUE, TRUE, self);
3297
3298   UNLOCK_CONTEXT (loop->context);
3299   
3300 #ifdef G_THREADS_ENABLED
3301   g_main_context_release (loop->context);
3302 #endif /* G_THREADS_ENABLED */    
3303   
3304   g_main_loop_unref (loop);
3305 }
3306
3307 /**
3308  * g_main_loop_quit:
3309  * @loop: a #GMainLoop
3310  * 
3311  * Stops a #GMainLoop from running. Any calls to g_main_loop_run()
3312  * for the loop will return. 
3313  *
3314  * Note that sources that have already been dispatched when 
3315  * g_main_loop_quit() is called will still be executed.
3316  **/
3317 void 
3318 g_main_loop_quit (GMainLoop *loop)
3319 {
3320   g_return_if_fail (loop != NULL);
3321   g_return_if_fail (g_atomic_int_get (&loop->ref_count) > 0);
3322
3323   LOCK_CONTEXT (loop->context);
3324   loop->is_running = FALSE;
3325   g_main_context_wakeup_unlocked (loop->context);
3326
3327 #ifdef G_THREADS_ENABLED
3328   if (loop->context->cond)
3329     g_cond_broadcast (loop->context->cond);
3330 #endif /* G_THREADS_ENABLED */
3331
3332   UNLOCK_CONTEXT (loop->context);
3333 }
3334
3335 /**
3336  * g_main_loop_is_running:
3337  * @loop: a #GMainLoop.
3338  * 
3339  * Checks to see if the main loop is currently being run via g_main_loop_run().
3340  * 
3341  * Return value: %TRUE if the mainloop is currently being run.
3342  **/
3343 gboolean
3344 g_main_loop_is_running (GMainLoop *loop)
3345 {
3346   g_return_val_if_fail (loop != NULL, FALSE);
3347   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, FALSE);
3348
3349   return loop->is_running;
3350 }
3351
3352 /**
3353  * g_main_loop_get_context:
3354  * @loop: a #GMainLoop.
3355  * 
3356  * Returns the #GMainContext of @loop.
3357  * 
3358  * Return value: the #GMainContext of @loop
3359  **/
3360 GMainContext *
3361 g_main_loop_get_context (GMainLoop *loop)
3362 {
3363   g_return_val_if_fail (loop != NULL, NULL);
3364   g_return_val_if_fail (g_atomic_int_get (&loop->ref_count) > 0, NULL);
3365  
3366   return loop->context;
3367 }
3368
3369 /* HOLDS: context's lock */
3370 static void
3371 g_main_context_poll (GMainContext *context,
3372                      gint          timeout,
3373                      gint          priority,
3374                      GPollFD      *fds,
3375                      gint          n_fds)
3376 {
3377 #ifdef  G_MAIN_POLL_DEBUG
3378   GTimer *poll_timer;
3379   GPollRec *pollrec;
3380   gint i;
3381 #endif
3382
3383   GPollFunc poll_func;
3384
3385   if (n_fds || timeout != 0)
3386     {
3387 #ifdef  G_MAIN_POLL_DEBUG
3388       if (_g_main_poll_debug)
3389         {
3390           g_print ("polling context=%p n=%d timeout=%d\n",
3391                    context, n_fds, timeout);
3392           poll_timer = g_timer_new ();
3393         }
3394 #endif
3395
3396       LOCK_CONTEXT (context);
3397
3398       poll_func = context->poll_func;
3399       
3400       UNLOCK_CONTEXT (context);
3401       if ((*poll_func) (fds, n_fds, timeout) < 0 && errno != EINTR)
3402         {
3403 #ifndef G_OS_WIN32
3404           g_warning ("poll(2) failed due to: %s.",
3405                      g_strerror (errno));
3406 #else
3407           /* If g_poll () returns -1, it has already called g_warning() */
3408 #endif
3409         }
3410       
3411 #ifdef  G_MAIN_POLL_DEBUG
3412       if (_g_main_poll_debug)
3413         {
3414           LOCK_CONTEXT (context);
3415
3416           g_print ("g_main_poll(%d) timeout: %d - elapsed %12.10f seconds",
3417                    n_fds,
3418                    timeout,
3419                    g_timer_elapsed (poll_timer, NULL));
3420           g_timer_destroy (poll_timer);
3421           pollrec = context->poll_records;
3422
3423           while (pollrec != NULL)
3424             {
3425               i = 0;
3426               while (i < n_fds)
3427                 {
3428                   if (fds[i].fd == pollrec->fd->fd &&
3429                       pollrec->fd->events &&
3430                       fds[i].revents)
3431                     {
3432                       g_print (" [" G_POLLFD_FORMAT " :", fds[i].fd);
3433                       if (fds[i].revents & G_IO_IN)
3434                         g_print ("i");
3435                       if (fds[i].revents & G_IO_OUT)
3436                         g_print ("o");
3437                       if (fds[i].revents & G_IO_PRI)
3438                         g_print ("p");
3439                       if (fds[i].revents & G_IO_ERR)
3440                         g_print ("e");
3441                       if (fds[i].revents & G_IO_HUP)
3442                         g_print ("h");
3443                       if (fds[i].revents & G_IO_NVAL)
3444                         g_print ("n");
3445                       g_print ("]");
3446                     }
3447                   i++;
3448                 }
3449               pollrec = pollrec->next;
3450             }
3451           g_print ("\n");
3452
3453           UNLOCK_CONTEXT (context);
3454         }
3455 #endif
3456     } /* if (n_fds || timeout != 0) */
3457 }
3458
3459 /**
3460  * g_main_context_add_poll:
3461  * @context: a #GMainContext (or %NULL for the default context)
3462  * @fd: a #GPollFD structure holding information about a file
3463  *      descriptor to watch.
3464  * @priority: the priority for this file descriptor which should be
3465  *      the same as the priority used for g_source_attach() to ensure that the
3466  *      file descriptor is polled whenever the results may be needed.
3467  * 
3468  * Adds a file descriptor to the set of file descriptors polled for
3469  * this context. This will very seldom be used directly. Instead
3470  * a typical event source will use g_source_add_poll() instead.
3471  **/
3472 void
3473 g_main_context_add_poll (GMainContext *context,
3474                          GPollFD      *fd,
3475                          gint          priority)
3476 {
3477   if (!context)
3478     context = g_main_context_default ();
3479   
3480   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3481   g_return_if_fail (fd);
3482
3483   LOCK_CONTEXT (context);
3484   g_main_context_add_poll_unlocked (context, priority, fd);
3485   UNLOCK_CONTEXT (context);
3486 }
3487
3488 /* HOLDS: main_loop_lock */
3489 static void 
3490 g_main_context_add_poll_unlocked (GMainContext *context,
3491                                   gint          priority,
3492                                   GPollFD      *fd)
3493 {
3494   GPollRec *prevrec, *nextrec;
3495   GPollRec *newrec = g_slice_new (GPollRec);
3496
3497   /* This file descriptor may be checked before we ever poll */
3498   fd->revents = 0;
3499   newrec->fd = fd;
3500   newrec->priority = priority;
3501
3502   prevrec = context->poll_records_tail;
3503   nextrec = NULL;
3504   while (prevrec && priority < prevrec->priority)
3505     {
3506       nextrec = prevrec;
3507       prevrec = prevrec->prev;
3508     }
3509
3510   if (prevrec)
3511     prevrec->next = newrec;
3512   else
3513     context->poll_records = newrec;
3514
3515   newrec->prev = prevrec;
3516   newrec->next = nextrec;
3517
3518   if (nextrec)
3519     nextrec->prev = newrec;
3520   else 
3521     context->poll_records_tail = newrec;
3522
3523   context->n_poll_records++;
3524
3525 #ifdef G_THREADS_ENABLED
3526   context->poll_changed = TRUE;
3527
3528   /* Now wake up the main loop if it is waiting in the poll() */
3529   g_main_context_wakeup_unlocked (context);
3530 #endif
3531 }
3532
3533 /**
3534  * g_main_context_remove_poll:
3535  * @context:a #GMainContext 
3536  * @fd: a #GPollFD descriptor previously added with g_main_context_add_poll()
3537  * 
3538  * Removes file descriptor from the set of file descriptors to be
3539  * polled for a particular context.
3540  **/
3541 void
3542 g_main_context_remove_poll (GMainContext *context,
3543                             GPollFD      *fd)
3544 {
3545   if (!context)
3546     context = g_main_context_default ();
3547   
3548   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3549   g_return_if_fail (fd);
3550
3551   LOCK_CONTEXT (context);
3552   g_main_context_remove_poll_unlocked (context, fd);
3553   UNLOCK_CONTEXT (context);
3554 }
3555
3556 static void
3557 g_main_context_remove_poll_unlocked (GMainContext *context,
3558                                      GPollFD      *fd)
3559 {
3560   GPollRec *pollrec, *prevrec, *nextrec;
3561
3562   prevrec = NULL;
3563   pollrec = context->poll_records;
3564
3565   while (pollrec)
3566     {
3567       nextrec = pollrec->next;
3568       if (pollrec->fd == fd)
3569         {
3570           if (prevrec != NULL)
3571             prevrec->next = nextrec;
3572           else
3573             context->poll_records = nextrec;
3574
3575           if (nextrec != NULL)
3576             nextrec->prev = prevrec;
3577           else
3578             context->poll_records_tail = prevrec;
3579
3580           g_slice_free (GPollRec, pollrec);
3581
3582           context->n_poll_records--;
3583           break;
3584         }
3585       prevrec = pollrec;
3586       pollrec = nextrec;
3587     }
3588
3589 #ifdef G_THREADS_ENABLED
3590   context->poll_changed = TRUE;
3591   
3592   /* Now wake up the main loop if it is waiting in the poll() */
3593   g_main_context_wakeup_unlocked (context);
3594 #endif
3595 }
3596
3597 /**
3598  * g_source_get_current_time:
3599  * @source:  a #GSource
3600  * @timeval: #GTimeVal structure in which to store current time.
3601  * 
3602  * Gets the "current time" to be used when checking 
3603  * this source. The advantage of calling this function over
3604  * calling g_get_current_time() directly is that when 
3605  * checking multiple sources, GLib can cache a single value
3606  * instead of having to repeatedly get the system time.
3607  *
3608  * Deprecated: 2.28: use g_source_get_time() instead
3609  **/
3610 void
3611 g_source_get_current_time (GSource  *source,
3612                            GTimeVal *timeval)
3613 {
3614   GMainContext *context;
3615   
3616   g_return_if_fail (source->context != NULL);
3617  
3618   context = source->context;
3619
3620   LOCK_CONTEXT (context);
3621
3622   if (!context->real_time_is_fresh)
3623     {
3624       context->real_time = g_get_real_time ();
3625       context->real_time_is_fresh = TRUE;
3626     }
3627   
3628   timeval->tv_sec = context->real_time / 1000000;
3629   timeval->tv_usec = context->real_time % 1000000;
3630   
3631   UNLOCK_CONTEXT (context);
3632 }
3633
3634 /**
3635  * g_source_get_time:
3636  * @source: a #GSource
3637  *
3638  * Gets the time to be used when checking this source. The advantage of
3639  * calling this function over calling g_get_monotonic_time() directly is
3640  * that when checking multiple sources, GLib can cache a single value
3641  * instead of having to repeatedly get the system monotonic time.
3642  *
3643  * The time here is the system monotonic time, if available, or some
3644  * other reasonable alternative otherwise.  See g_get_monotonic_time().
3645  *
3646  * Returns: the monotonic time in microseconds
3647  *
3648  * Since: 2.28
3649  **/
3650 gint64
3651 g_source_get_time (GSource *source)
3652 {
3653   GMainContext *context;
3654   gint64 result;
3655
3656   g_return_val_if_fail (source->context != NULL, 0);
3657
3658   context = source->context;
3659
3660   LOCK_CONTEXT (context);
3661
3662   if (!context->time_is_fresh)
3663     {
3664       context->time = g_get_monotonic_time ();
3665       context->time_is_fresh = TRUE;
3666     }
3667
3668   result = context->time;
3669
3670   UNLOCK_CONTEXT (context);
3671
3672   return result;
3673 }
3674
3675 /**
3676  * g_main_context_set_poll_func:
3677  * @context: a #GMainContext
3678  * @func: the function to call to poll all file descriptors
3679  * 
3680  * Sets the function to use to handle polling of file descriptors. It
3681  * will be used instead of the poll() system call 
3682  * (or GLib's replacement function, which is used where 
3683  * poll() isn't available).
3684  *
3685  * This function could possibly be used to integrate the GLib event
3686  * loop with an external event loop.
3687  **/
3688 void
3689 g_main_context_set_poll_func (GMainContext *context,
3690                               GPollFunc     func)
3691 {
3692   if (!context)
3693     context = g_main_context_default ();
3694   
3695   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3696
3697   LOCK_CONTEXT (context);
3698   
3699   if (func)
3700     context->poll_func = func;
3701   else
3702     context->poll_func = g_poll;
3703
3704   UNLOCK_CONTEXT (context);
3705 }
3706
3707 /**
3708  * g_main_context_get_poll_func:
3709  * @context: a #GMainContext
3710  * 
3711  * Gets the poll function set by g_main_context_set_poll_func().
3712  * 
3713  * Return value: the poll function
3714  **/
3715 GPollFunc
3716 g_main_context_get_poll_func (GMainContext *context)
3717 {
3718   GPollFunc result;
3719   
3720   if (!context)
3721     context = g_main_context_default ();
3722   
3723   g_return_val_if_fail (g_atomic_int_get (&context->ref_count) > 0, NULL);
3724
3725   LOCK_CONTEXT (context);
3726   result = context->poll_func;
3727   UNLOCK_CONTEXT (context);
3728
3729   return result;
3730 }
3731
3732 static void
3733 _g_main_wake_up_all_contexts (void)
3734 {
3735   GSList *list;
3736
3737   /* We were woken up.  Wake up all other contexts in all other threads */
3738   G_LOCK (main_context_list);
3739   for (list = main_context_list; list; list = list->next)
3740     {
3741       GMainContext *context = list->data;
3742
3743       LOCK_CONTEXT (context);
3744       g_main_context_wakeup_unlocked (context);
3745       UNLOCK_CONTEXT (context);
3746     }
3747   G_UNLOCK (main_context_list);
3748 }
3749
3750
3751 /* HOLDS: context's lock */
3752 /* Wake the main loop up from a poll() */
3753 static void
3754 g_main_context_wakeup_unlocked (GMainContext *context)
3755 {
3756 #ifdef G_THREADS_ENABLED
3757   if (g_thread_supported() && context->poll_waiting)
3758     {
3759       context->poll_waiting = FALSE;
3760       g_wakeup_signal (context->wakeup);
3761     }
3762 #endif
3763 }
3764
3765 /**
3766  * g_main_context_wakeup:
3767  * @context: a #GMainContext
3768  * 
3769  * If @context is currently waiting in a poll(), interrupt
3770  * the poll(), and continue the iteration process.
3771  **/
3772 void
3773 g_main_context_wakeup (GMainContext *context)
3774 {
3775   if (!context)
3776     context = g_main_context_default ();
3777   
3778   g_return_if_fail (g_atomic_int_get (&context->ref_count) > 0);
3779
3780   LOCK_CONTEXT (context);
3781   g_main_context_wakeup_unlocked (context);
3782   UNLOCK_CONTEXT (context);
3783 }
3784
3785 /**
3786  * g_main_context_is_owner:
3787  * @context: a #GMainContext
3788  * 
3789  * Determines whether this thread holds the (recursive)
3790  * ownership of this #GMaincontext. This is useful to
3791  * know before waiting on another thread that may be
3792  * blocking to get ownership of @context.
3793  *
3794  * Returns: %TRUE if current thread is owner of @context.
3795  *
3796  * Since: 2.10
3797  **/
3798 gboolean
3799 g_main_context_is_owner (GMainContext *context)
3800 {
3801   gboolean is_owner;
3802
3803   if (!context)
3804     context = g_main_context_default ();
3805
3806 #ifdef G_THREADS_ENABLED
3807   LOCK_CONTEXT (context);
3808   is_owner = context->owner == G_THREAD_SELF;
3809   UNLOCK_CONTEXT (context);
3810 #else
3811   is_owner = TRUE;
3812 #endif
3813
3814   return is_owner;
3815 }
3816
3817 /* Timeouts */
3818
3819 static void
3820 g_timeout_set_expiration (GTimeoutSource *timeout_source,
3821                           gint64          current_time)
3822 {
3823   timeout_source->expiration = current_time +
3824                                (guint64) timeout_source->interval * 1000;
3825
3826   if (timeout_source->seconds)
3827     {
3828       gint64 remainder;
3829       static gint timer_perturb = -1;
3830
3831       if (timer_perturb == -1)
3832         {
3833           /*
3834            * we want a per machine/session unique 'random' value; try the dbus
3835            * address first, that has a UUID in it. If there is no dbus, use the
3836            * hostname for hashing.
3837            */
3838           const char *session_bus_address = g_getenv ("DBUS_SESSION_BUS_ADDRESS");
3839           if (!session_bus_address)
3840             session_bus_address = g_getenv ("HOSTNAME");
3841           if (session_bus_address)
3842             timer_perturb = ABS ((gint) g_str_hash (session_bus_address)) % 1000000;
3843           else
3844             timer_perturb = 0;
3845         }
3846
3847       /* We want the microseconds part of the timeout to land on the
3848        * 'timer_perturb' mark, but we need to make sure we don't try to
3849        * set the timeout in the past.  We do this by ensuring that we
3850        * always only *increase* the expiration time by adding a full
3851        * second in the case that the microsecond portion decreases.
3852        */
3853       timeout_source->expiration -= timer_perturb;
3854
3855       remainder = timeout_source->expiration % 1000000;
3856       if (remainder >= 1000000/4)
3857         timeout_source->expiration += 1000000;
3858
3859       timeout_source->expiration -= remainder;
3860       timeout_source->expiration += timer_perturb;
3861     }
3862 }
3863
3864 static gboolean
3865 g_timeout_prepare (GSource *source,
3866                    gint    *timeout)
3867 {
3868   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3869   gint64 now = g_source_get_time (source);
3870
3871   if (now < timeout_source->expiration)
3872     {
3873       /* Round up to ensure that we don't try again too early */
3874       *timeout = (timeout_source->expiration - now + 999) / 1000;
3875       return FALSE;
3876     }
3877
3878   *timeout = 0;
3879   return TRUE;
3880 }
3881
3882 static gboolean 
3883 g_timeout_check (GSource *source)
3884 {
3885   GTimeoutSource *timeout_source = (GTimeoutSource *) source;
3886   gint64 now = g_source_get_time (source);
3887
3888   return timeout_source->expiration <= now;
3889 }
3890
3891 static gboolean
3892 g_timeout_dispatch (GSource     *source,
3893                     GSourceFunc  callback,
3894                     gpointer     user_data)
3895 {
3896   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3897   gboolean again;
3898
3899   if (!callback)
3900     {
3901       g_warning ("Timeout source dispatched without callback\n"
3902                  "You must call g_source_set_callback().");
3903       return FALSE;
3904     }
3905
3906   again = callback (user_data);
3907
3908   if (again)
3909     g_timeout_set_expiration (timeout_source, g_source_get_time (source));
3910
3911   return again;
3912 }
3913
3914 /**
3915  * g_timeout_source_new:
3916  * @interval: the timeout interval in milliseconds.
3917  * 
3918  * Creates a new timeout source.
3919  *
3920  * The source will not initially be associated with any #GMainContext
3921  * and must be added to one with g_source_attach() before it will be
3922  * executed.
3923  *
3924  * The interval given is in terms of monotonic time, not wall clock
3925  * time.  See g_get_monotonic_time().
3926  * 
3927  * Return value: the newly-created timeout source
3928  **/
3929 GSource *
3930 g_timeout_source_new (guint interval)
3931 {
3932   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3933   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3934
3935   timeout_source->interval = interval;
3936   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3937
3938   return source;
3939 }
3940
3941 /**
3942  * g_timeout_source_new_seconds:
3943  * @interval: the timeout interval in seconds
3944  *
3945  * Creates a new timeout source.
3946  *
3947  * The source will not initially be associated with any #GMainContext
3948  * and must be added to one with g_source_attach() before it will be
3949  * executed.
3950  *
3951  * The scheduling granularity/accuracy of this timeout source will be
3952  * in seconds.
3953  *
3954  * The interval given in terms of monotonic time, not wall clock time.
3955  * See g_get_monotonic_time().
3956  *
3957  * Return value: the newly-created timeout source
3958  *
3959  * Since: 2.14  
3960  **/
3961 GSource *
3962 g_timeout_source_new_seconds (guint interval)
3963 {
3964   GSource *source = g_source_new (&g_timeout_funcs, sizeof (GTimeoutSource));
3965   GTimeoutSource *timeout_source = (GTimeoutSource *)source;
3966
3967   timeout_source->interval = 1000 * interval;
3968   timeout_source->seconds = TRUE;
3969
3970   g_timeout_set_expiration (timeout_source, g_get_monotonic_time ());
3971
3972   return source;
3973 }
3974
3975
3976 /**
3977  * g_timeout_add_full:
3978  * @priority: the priority of the timeout source. Typically this will be in
3979  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
3980  * @interval: the time between calls to the function, in milliseconds
3981  *             (1/1000ths of a second)
3982  * @function: function to call
3983  * @data:     data to pass to @function
3984  * @notify:   function to call when the timeout is removed, or %NULL
3985  * 
3986  * Sets a function to be called at regular intervals, with the given
3987  * priority.  The function is called repeatedly until it returns
3988  * %FALSE, at which point the timeout is automatically destroyed and
3989  * the function will not be called again.  The @notify function is
3990  * called when the timeout is destroyed.  The first call to the
3991  * function will be at the end of the first @interval.
3992  *
3993  * Note that timeout functions may be delayed, due to the processing of other
3994  * event sources. Thus they should not be relied on for precise timing.
3995  * After each call to the timeout function, the time of the next
3996  * timeout is recalculated based on the current time and the given interval
3997  * (it does not try to 'catch up' time lost in delays).
3998  *
3999  * This internally creates a main loop source using g_timeout_source_new()
4000  * and attaches it to the main loop context using g_source_attach(). You can
4001  * do these steps manually if you need greater control.
4002  *
4003  * The interval given in terms of monotonic time, not wall clock time.
4004  * See g_get_monotonic_time().
4005  * 
4006  * Return value: the ID (greater than 0) of the event source.
4007  * Rename to: g_timeout_add
4008  **/
4009 guint
4010 g_timeout_add_full (gint           priority,
4011                     guint          interval,
4012                     GSourceFunc    function,
4013                     gpointer       data,
4014                     GDestroyNotify notify)
4015 {
4016   GSource *source;
4017   guint id;
4018   
4019   g_return_val_if_fail (function != NULL, 0);
4020
4021   source = g_timeout_source_new (interval);
4022
4023   if (priority != G_PRIORITY_DEFAULT)
4024     g_source_set_priority (source, priority);
4025
4026   g_source_set_callback (source, function, data, notify);
4027   id = g_source_attach (source, NULL);
4028   g_source_unref (source);
4029
4030   return id;
4031 }
4032
4033 /**
4034  * g_timeout_add:
4035  * @interval: the time between calls to the function, in milliseconds
4036  *             (1/1000ths of a second)
4037  * @function: function to call
4038  * @data:     data to pass to @function
4039  * 
4040  * Sets a function to be called at regular intervals, with the default
4041  * priority, #G_PRIORITY_DEFAULT.  The function is called repeatedly
4042  * until it returns %FALSE, at which point the timeout is automatically
4043  * destroyed and the function will not be called again.  The first call
4044  * to the function will be at the end of the first @interval.
4045  *
4046  * Note that timeout functions may be delayed, due to the processing of other
4047  * event sources. Thus they should not be relied on for precise timing.
4048  * After each call to the timeout function, the time of the next
4049  * timeout is recalculated based on the current time and the given interval
4050  * (it does not try to 'catch up' time lost in delays).
4051  *
4052  * If you want to have a timer in the "seconds" range and do not care
4053  * about the exact time of the first call of the timer, use the
4054  * g_timeout_add_seconds() function; this function allows for more
4055  * optimizations and more efficient system power usage.
4056  *
4057  * This internally creates a main loop source using g_timeout_source_new()
4058  * and attaches it to the main loop context using g_source_attach(). You can
4059  * do these steps manually if you need greater control.
4060  * 
4061  * The interval given is in terms of monotonic time, not wall clock
4062  * time.  See g_get_monotonic_time().
4063  * 
4064  * Return value: the ID (greater than 0) of the event source.
4065  **/
4066 guint
4067 g_timeout_add (guint32        interval,
4068                GSourceFunc    function,
4069                gpointer       data)
4070 {
4071   return g_timeout_add_full (G_PRIORITY_DEFAULT, 
4072                              interval, function, data, NULL);
4073 }
4074
4075 /**
4076  * g_timeout_add_seconds_full:
4077  * @priority: the priority of the timeout source. Typically this will be in
4078  *            the range between #G_PRIORITY_DEFAULT and #G_PRIORITY_HIGH.
4079  * @interval: the time between calls to the function, in seconds
4080  * @function: function to call
4081  * @data:     data to pass to @function
4082  * @notify:   function to call when the timeout is removed, or %NULL
4083  *
4084  * Sets a function to be called at regular intervals, with @priority.
4085  * The function is called repeatedly until it returns %FALSE, at which
4086  * point the timeout is automatically destroyed and the function will
4087  * not be called again.
4088  *
4089  * Unlike g_timeout_add(), this function operates at whole second granularity.
4090  * The initial starting point of the timer is determined by the implementation
4091  * and the implementation is expected to group multiple timers together so that
4092  * they fire all at the same time.
4093  * To allow this grouping, the @interval to the first timer is rounded
4094  * and can deviate up to one second from the specified interval.
4095  * Subsequent timer iterations will generally run at the specified interval.
4096  *
4097  * Note that timeout functions may be delayed, due to the processing of other
4098  * event sources. Thus they should not be relied on for precise timing.
4099  * After each call to the timeout function, the time of the next
4100  * timeout is recalculated based on the current time and the given @interval
4101  *
4102  * If you want timing more precise than whole seconds, use g_timeout_add()
4103  * instead.
4104  *
4105  * The grouping of timers to fire at the same time results in a more power
4106  * and CPU efficient behavior so if your timer is in multiples of seconds
4107  * and you don't require the first timer exactly one second from now, the
4108  * use of g_timeout_add_seconds() is preferred over g_timeout_add().
4109  *
4110  * This internally creates a main loop source using 
4111  * g_timeout_source_new_seconds() and attaches it to the main loop context 
4112  * using g_source_attach(). You can do these steps manually if you need 
4113  * greater control.
4114  * 
4115  * The interval given is in terms of monotonic time, not wall clock
4116  * time.  See g_get_monotonic_time().
4117  * 
4118  * Return value: the ID (greater than 0) of the event source.
4119  *
4120  * Rename to: g_timeout_add_seconds
4121  * Since: 2.14
4122  **/
4123 guint
4124 g_timeout_add_seconds_full (gint           priority,
4125                             guint32        interval,
4126                             GSourceFunc    function,
4127                             gpointer       data,
4128                             GDestroyNotify notify)
4129 {
4130   GSource *source;
4131   guint id;
4132
4133   g_return_val_if_fail (function != NULL, 0);
4134
4135   source = g_timeout_source_new_seconds (interval);
4136
4137   if (priority != G_PRIORITY_DEFAULT)
4138     g_source_set_priority (source, priority);
4139
4140   g_source_set_callback (source, function, data, notify);
4141   id = g_source_attach (source, NULL);
4142   g_source_unref (source);
4143
4144   return id;
4145 }
4146
4147 /**
4148  * g_timeout_add_seconds:
4149  * @interval: the time between calls to the function, in seconds
4150  * @function: function to call
4151  * @data: data to pass to @function
4152  *
4153  * Sets a function to be called at regular intervals with the default
4154  * priority, #G_PRIORITY_DEFAULT. The function is called repeatedly until
4155  * it returns %FALSE, at which point the timeout is automatically destroyed
4156  * and the function will not be called again.
4157  *
4158  * This internally creates a main loop source using
4159  * g_timeout_source_new_seconds() and attaches it to the main loop context
4160  * using g_source_attach(). You can do these steps manually if you need
4161  * greater control. Also see g_timeout_add_seconds_full().
4162  *
4163  * Note that the first call of the timer may not be precise for timeouts
4164  * of one second. If you need finer precision and have such a timeout,
4165  * you may want to use g_timeout_add() instead.
4166  *
4167  * The interval given is in terms of monotonic time, not wall clock
4168  * time.  See g_get_monotonic_time().
4169  * 
4170  * Return value: the ID (greater than 0) of the event source.
4171  *
4172  * Since: 2.14
4173  **/
4174 guint
4175 g_timeout_add_seconds (guint       interval,
4176                        GSourceFunc function,
4177                        gpointer    data)
4178 {
4179   g_return_val_if_fail (function != NULL, 0);
4180
4181   return g_timeout_add_seconds_full (G_PRIORITY_DEFAULT, interval, function, data, NULL);
4182 }
4183
4184 /* Child watch functions */
4185
4186 #ifdef G_OS_WIN32
4187
4188 static gboolean
4189 g_child_watch_prepare (GSource *source,
4190                        gint    *timeout)
4191 {
4192   *timeout = -1;
4193   return FALSE;
4194 }
4195
4196
4197 static gboolean 
4198 g_child_watch_check (GSource  *source)
4199 {
4200   GChildWatchSource *child_watch_source;
4201   gboolean child_exited;
4202
4203   child_watch_source = (GChildWatchSource *) source;
4204
4205   child_exited = child_watch_source->poll.revents & G_IO_IN;
4206
4207   if (child_exited)
4208     {
4209       DWORD child_status;
4210
4211       /*
4212        * Note: We do _not_ check for the special value of STILL_ACTIVE
4213        * since we know that the process has exited and doing so runs into
4214        * problems if the child process "happens to return STILL_ACTIVE(259)"
4215        * as Microsoft's Platform SDK puts it.
4216        */
4217       if (!GetExitCodeProcess (child_watch_source->pid, &child_status))
4218         {
4219           gchar *emsg = g_win32_error_message (GetLastError ());
4220           g_warning (G_STRLOC ": GetExitCodeProcess() failed: %s", emsg);
4221           g_free (emsg);
4222
4223           child_watch_source->child_status = -1;
4224         }
4225       else
4226         child_watch_source->child_status = child_status;
4227     }
4228
4229   return child_exited;
4230 }
4231
4232 #else /* G_OS_WIN32 */
4233
4234 static gboolean
4235 check_for_child_exited (GSource *source)
4236 {
4237   GChildWatchSource *child_watch_source;
4238   gint count;
4239
4240   /* protect against another SIGCHLD in the middle of this call */
4241   count = child_watch_count;
4242
4243   child_watch_source = (GChildWatchSource *) source;
4244
4245   if (child_watch_source->child_exited)
4246     return TRUE;
4247
4248   if (child_watch_source->count < count)
4249     {
4250       gint child_status;
4251
4252       if (waitpid (child_watch_source->pid, &child_status, WNOHANG) > 0)
4253         {
4254           child_watch_source->child_status = child_status;
4255           child_watch_source->child_exited = TRUE;
4256         }
4257       child_watch_source->count = count;
4258     }
4259
4260   return child_watch_source->child_exited;
4261 }
4262
4263 static gboolean
4264 g_child_watch_prepare (GSource *source,
4265                        gint    *timeout)
4266 {
4267   *timeout = -1;
4268
4269   return check_for_child_exited (source);
4270 }
4271
4272 static gboolean 
4273 g_child_watch_check (GSource  *source)
4274 {
4275   return check_for_child_exited (source);
4276 }
4277
4278 static gboolean
4279 check_for_signal_delivery (GSource *source)
4280 {
4281   GUnixSignalWatchSource *unix_signal_source = (GUnixSignalWatchSource*) source;
4282   gboolean delivered;
4283
4284   G_LOCK (unix_signal_lock);
4285   if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4286     {
4287       switch (unix_signal_source->signum)
4288         {
4289         case SIGHUP:
4290           delivered = unix_signal_state.sighup_delivered;
4291           break;
4292         case SIGINT:
4293           delivered = unix_signal_state.sigint_delivered;
4294           break;
4295         case SIGTERM:
4296           delivered = unix_signal_state.sigterm_delivered;
4297           break;
4298         default:
4299           g_assert_not_reached ();
4300           delivered = FALSE;
4301           break;
4302         }
4303     }
4304   else
4305     {
4306       g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4307       delivered = unix_signal_source->pending;
4308     }
4309   G_UNLOCK (unix_signal_lock);
4310
4311   return delivered;
4312 }
4313
4314 static gboolean
4315 g_unix_signal_watch_prepare (GSource *source,
4316                              gint    *timeout)
4317 {
4318   *timeout = -1;
4319
4320   return check_for_signal_delivery (source);
4321 }
4322
4323 static gboolean 
4324 g_unix_signal_watch_check (GSource  *source)
4325 {
4326   return check_for_signal_delivery (source);
4327 }
4328
4329 static gboolean
4330 g_unix_signal_watch_dispatch (GSource    *source, 
4331                               GSourceFunc callback,
4332                               gpointer    user_data)
4333 {
4334   GUnixSignalWatchSource *unix_signal_source;
4335
4336   unix_signal_source = (GUnixSignalWatchSource *) source;
4337
4338   if (!callback)
4339     {
4340       g_warning ("Unix signal source dispatched without callback\n"
4341                  "You must call g_source_set_callback().");
4342       return FALSE;
4343     }
4344
4345   (callback) (user_data);
4346   
4347   G_LOCK (unix_signal_lock);
4348   if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4349     {
4350       switch (unix_signal_source->signum)
4351         {
4352         case SIGHUP:
4353           unix_signal_state.sighup_delivered = FALSE;
4354           break;
4355         case SIGINT:
4356           unix_signal_state.sigint_delivered = FALSE;
4357           break;
4358         case SIGTERM:
4359           unix_signal_state.sigterm_delivered = FALSE;
4360           break;
4361         }
4362     }
4363   else
4364     {
4365       g_assert (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED);
4366       unix_signal_source->pending = FALSE;
4367     }
4368   G_UNLOCK (unix_signal_lock);
4369
4370   return TRUE;
4371 }
4372
4373 static void
4374 ensure_unix_signal_handler_installed_unlocked (int signum)
4375 {
4376   struct sigaction action;
4377   GError *error = NULL;
4378
4379   if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4380     {
4381       sigemptyset (&unix_signal_mask);
4382     }
4383
4384   if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED
4385       || unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_SINGLE)
4386     {
4387       if (!g_thread_supported ())
4388         {
4389           /* There is nothing to do for initializing in the non-threaded
4390            * case.
4391            */
4392           if (unix_signal_init_state == UNIX_SIGNAL_UNINITIALIZED)
4393             unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_SINGLE;
4394         }
4395       else
4396         {
4397           if (!g_unix_open_pipe (unix_signal_wake_up_pipe, FD_CLOEXEC, &error))
4398             g_error ("Cannot create UNIX signal wake up pipe: %s\n", error->message);
4399           g_unix_set_fd_nonblocking (unix_signal_wake_up_pipe[1], TRUE, NULL);
4400           
4401           /* We create a helper thread that polls on the wakeup pipe indefinitely */
4402           if (g_thread_create (unix_signal_helper_thread, NULL, FALSE, &error) == NULL)
4403             g_error ("Cannot create a thread to monitor UNIX signals: %s\n", error->message);
4404           
4405           unix_signal_init_state = UNIX_SIGNAL_INITIALIZED_THREADED;
4406         }
4407     }
4408
4409   if (sigismember (&unix_signal_mask, signum))
4410     return;
4411
4412   sigaddset (&unix_signal_mask, signum);
4413
4414   action.sa_handler = g_unix_signal_handler;
4415   sigemptyset (&action.sa_mask);
4416   action.sa_flags = SA_RESTART | SA_NOCLDSTOP;
4417   sigaction (signum, &action, NULL);
4418 }
4419
4420 GSource *
4421 _g_main_create_unix_signal_watch (int signum)
4422 {
4423   GSource *source;
4424   GUnixSignalWatchSource *unix_signal_source;
4425
4426   source = g_source_new (&g_unix_signal_funcs, sizeof (GUnixSignalWatchSource));
4427   unix_signal_source = (GUnixSignalWatchSource *) source;
4428
4429   unix_signal_source->signum = signum;
4430   unix_signal_source->pending = FALSE;
4431
4432   G_LOCK (unix_signal_lock);
4433   ensure_unix_signal_handler_installed_unlocked (signum);
4434   unix_signal_watches = g_slist_prepend (unix_signal_watches, unix_signal_source);
4435   G_UNLOCK (unix_signal_lock);
4436
4437   return source;
4438 }
4439
4440 static void 
4441 g_unix_signal_watch_finalize (GSource    *source)
4442 {
4443   G_LOCK (unix_signal_lock);
4444   unix_signal_watches = g_slist_remove (unix_signal_watches, source);
4445   G_UNLOCK (unix_signal_lock);
4446 }
4447
4448 #endif /* G_OS_WIN32 */
4449
4450 static gboolean
4451 g_child_watch_dispatch (GSource    *source, 
4452                         GSourceFunc callback,
4453                         gpointer    user_data)
4454 {
4455   GChildWatchSource *child_watch_source;
4456   GChildWatchFunc child_watch_callback = (GChildWatchFunc) callback;
4457
4458   child_watch_source = (GChildWatchSource *) source;
4459
4460   if (!callback)
4461     {
4462       g_warning ("Child watch source dispatched without callback\n"
4463                  "You must call g_source_set_callback().");
4464       return FALSE;
4465     }
4466
4467   (child_watch_callback) (child_watch_source->pid, child_watch_source->child_status, user_data);
4468
4469   /* We never keep a child watch source around as the child is gone */
4470   return FALSE;
4471 }
4472
4473 #ifndef G_OS_WIN32
4474
4475 static void
4476 g_unix_signal_handler (int signum)
4477 {
4478   if (signum == SIGCHLD)
4479     child_watch_count ++;
4480
4481   if (unix_signal_init_state == UNIX_SIGNAL_INITIALIZED_THREADED)
4482     {
4483       char buf[1];
4484       switch (signum)
4485         {
4486         case SIGCHLD:
4487           buf[0] = _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR;
4488           break;
4489         case SIGHUP:
4490           buf[0] = _UNIX_SIGNAL_PIPE_SIGHUP_CHAR;
4491           break;
4492         case SIGINT:
4493           buf[0] = _UNIX_SIGNAL_PIPE_SIGINT_CHAR;
4494           break;
4495         case SIGTERM:
4496           buf[0] = _UNIX_SIGNAL_PIPE_SIGTERM_CHAR;
4497           break;
4498         default:
4499           /* Shouldn't happen */
4500           return;
4501         }
4502       write (unix_signal_wake_up_pipe[1], buf, 1);
4503     }
4504   else
4505     {
4506       /* We count on the signal interrupting the poll in the same thread. */
4507       switch (signum)
4508         {
4509         case SIGCHLD:
4510           /* Nothing to do - the handler will call waitpid() */
4511           break;
4512         case SIGHUP:
4513           unix_signal_state.sighup_delivered = TRUE;
4514           break;
4515         case SIGINT:
4516           unix_signal_state.sigint_delivered = TRUE;
4517           break;
4518         case SIGTERM:
4519           unix_signal_state.sigterm_delivered = TRUE;
4520           break;
4521         default:
4522           g_assert_not_reached ();
4523           break;
4524         }
4525     }
4526 }
4527  
4528 static void
4529 deliver_unix_signal (int signum)
4530 {
4531   GSList *iter;
4532   g_assert (signum == SIGHUP || signum == SIGINT || signum == SIGTERM);
4533
4534   G_LOCK (unix_signal_lock);
4535   for (iter = unix_signal_watches; iter; iter = iter->next)
4536     {
4537       GUnixSignalWatchSource *source = iter->data;
4538
4539       if (source->signum != signum)
4540         continue;
4541       
4542       source->pending = TRUE;
4543     }
4544   G_UNLOCK (unix_signal_lock);
4545 }
4546
4547 /*
4548  * This thread is created whenever anything in GLib needs
4549  * to deal with UNIX signals; at present, just SIGCHLD
4550  * from g_child_watch_source_new().
4551  *
4552  * Note: We could eventually make this thread a more public interface
4553  * and allow e.g. GDBus to use it instead of its own worker thread.
4554  */
4555 static gpointer
4556 unix_signal_helper_thread (gpointer data) 
4557 {
4558   while (1)
4559     {
4560       gchar b[128];
4561       ssize_t i, bytes_read;
4562       gboolean sigterm_received = FALSE;
4563       gboolean sigint_received = FALSE;
4564       gboolean sighup_received = FALSE;
4565
4566       bytes_read = read (unix_signal_wake_up_pipe[0], b, sizeof (b));
4567       if (bytes_read < 0)
4568         {
4569           g_warning ("Failed to read from child watch wake up pipe: %s",
4570                      strerror (errno));
4571           /* Not much we can do here sanely; just wait a second and hope
4572            * it was transient.
4573            */
4574           g_usleep (G_USEC_PER_SEC);
4575           continue;
4576         }
4577       for (i = 0; i < bytes_read; i++)
4578         {
4579           switch (b[i])
4580             {
4581             case _UNIX_SIGNAL_PIPE_SIGCHLD_CHAR:
4582               /* The child watch source will call waitpid() in its
4583                * prepare() and check() methods; however, we don't
4584                * know which pid exited, so we need to wake up
4585                * all contexts.  Note: actually we could get the pid
4586                * from the "siginfo_t" via the handler, but to pass
4587                * that info down the pipe would require a more structured
4588                * data stream (as opposed to a single byte).
4589                */
4590               break;
4591             case _UNIX_SIGNAL_PIPE_SIGTERM_CHAR:
4592               sigterm_received = TRUE;
4593               break;
4594             case _UNIX_SIGNAL_PIPE_SIGHUP_CHAR:
4595               sighup_received = TRUE;
4596               break;
4597             case _UNIX_SIGNAL_PIPE_SIGINT_CHAR:
4598               sigint_received = TRUE;
4599               break;
4600             default:
4601               g_warning ("Invalid char '%c' read from child watch pipe", b[i]);
4602               break;
4603             }
4604         }
4605       if (sigterm_received)
4606         deliver_unix_signal (SIGTERM);
4607       if (sigint_received)
4608         deliver_unix_signal (SIGINT);
4609       if (sighup_received)
4610         deliver_unix_signal (SIGHUP);
4611       _g_main_wake_up_all_contexts ();
4612     }
4613 }
4614
4615 static void
4616 g_child_watch_source_init (void)
4617 {
4618   G_LOCK (unix_signal_lock);
4619   ensure_unix_signal_handler_installed_unlocked (SIGCHLD);
4620   G_UNLOCK (unix_signal_lock);
4621 }
4622
4623 #endif /* !G_OS_WIN32 */
4624
4625 /**
4626  * g_child_watch_source_new:
4627  * @pid: process to watch. On POSIX the pid of a child process. On
4628  * Windows a handle for a process (which doesn't have to be a child).
4629  * 
4630  * Creates a new child_watch source.
4631  *
4632  * The source will not initially be associated with any #GMainContext
4633  * and must be added to one with g_source_attach() before it will be
4634  * executed.
4635  * 
4636  * Note that child watch sources can only be used in conjunction with
4637  * <literal>g_spawn...</literal> when the %G_SPAWN_DO_NOT_REAP_CHILD
4638  * flag is used.
4639  *
4640  * Note that on platforms where #GPid must be explicitly closed
4641  * (see g_spawn_close_pid()) @pid must not be closed while the
4642  * source is still active. Typically, you will want to call
4643  * g_spawn_close_pid() in the callback function for the source.
4644  *
4645  * Note further that using g_child_watch_source_new() is not 
4646  * compatible with calling <literal>waitpid(-1)</literal> in 
4647  * the application. Calling waitpid() for individual pids will
4648  * still work fine. 
4649  * 
4650  * Return value: the newly-created child watch source
4651  *
4652  * Since: 2.4
4653  **/
4654 GSource *
4655 g_child_watch_source_new (GPid pid)
4656 {
4657   GSource *source = g_source_new (&g_child_watch_funcs, sizeof (GChildWatchSource));
4658   GChildWatchSource *child_watch_source = (GChildWatchSource *)source;
4659
4660 #ifdef G_OS_WIN32
4661   child_watch_source->poll.fd = (gintptr) pid;
4662   child_watch_source->poll.events = G_IO_IN;
4663
4664   g_source_add_poll (source, &child_watch_source->poll);
4665 #else /* G_OS_WIN32 */
4666   g_child_watch_source_init ();
4667 #endif /* G_OS_WIN32 */
4668
4669   child_watch_source->pid = pid;
4670
4671   return source;
4672 }
4673
4674 /**
4675  * g_child_watch_add_full:
4676  * @priority: the priority of the idle source. Typically this will be in the
4677  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4678  * @pid:      process to watch. On POSIX the pid of a child process. On
4679  * Windows a handle for a process (which doesn't have to be a child).
4680  * @function: function to call
4681  * @data:     data to pass to @function
4682  * @notify:   function to call when the idle is removed, or %NULL
4683  * 
4684  * Sets a function to be called when the child indicated by @pid 
4685  * exits, at the priority @priority.
4686  *
4687  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4688  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4689  * the spawn function for the child watching to work.
4690  * 
4691  * Note that on platforms where #GPid must be explicitly closed
4692  * (see g_spawn_close_pid()) @pid must not be closed while the
4693  * source is still active. Typically, you will want to call
4694  * g_spawn_close_pid() in the callback function for the source.
4695  * 
4696  * GLib supports only a single callback per process id.
4697  *
4698  * This internally creates a main loop source using 
4699  * g_child_watch_source_new() and attaches it to the main loop context 
4700  * using g_source_attach(). You can do these steps manually if you 
4701  * need greater control.
4702  *
4703  * Return value: the ID (greater than 0) of the event source.
4704  *
4705  * Rename to: g_child_watch_add
4706  * Since: 2.4
4707  **/
4708 guint
4709 g_child_watch_add_full (gint            priority,
4710                         GPid            pid,
4711                         GChildWatchFunc function,
4712                         gpointer        data,
4713                         GDestroyNotify  notify)
4714 {
4715   GSource *source;
4716   guint id;
4717   
4718   g_return_val_if_fail (function != NULL, 0);
4719
4720   source = g_child_watch_source_new (pid);
4721
4722   if (priority != G_PRIORITY_DEFAULT)
4723     g_source_set_priority (source, priority);
4724
4725   g_source_set_callback (source, (GSourceFunc) function, data, notify);
4726   id = g_source_attach (source, NULL);
4727   g_source_unref (source);
4728
4729   return id;
4730 }
4731
4732 /**
4733  * g_child_watch_add:
4734  * @pid:      process id to watch. On POSIX the pid of a child process. On
4735  * Windows a handle for a process (which doesn't have to be a child).
4736  * @function: function to call
4737  * @data:     data to pass to @function
4738  * 
4739  * Sets a function to be called when the child indicated by @pid 
4740  * exits, at a default priority, #G_PRIORITY_DEFAULT.
4741  * 
4742  * If you obtain @pid from g_spawn_async() or g_spawn_async_with_pipes() 
4743  * you will need to pass #G_SPAWN_DO_NOT_REAP_CHILD as flag to 
4744  * the spawn function for the child watching to work.
4745  * 
4746  * Note that on platforms where #GPid must be explicitly closed
4747  * (see g_spawn_close_pid()) @pid must not be closed while the
4748  * source is still active. Typically, you will want to call
4749  * g_spawn_close_pid() in the callback function for the source.
4750  *
4751  * GLib supports only a single callback per process id.
4752  *
4753  * This internally creates a main loop source using 
4754  * g_child_watch_source_new() and attaches it to the main loop context 
4755  * using g_source_attach(). You can do these steps manually if you 
4756  * need greater control.
4757  *
4758  * Return value: the ID (greater than 0) of the event source.
4759  *
4760  * Since: 2.4
4761  **/
4762 guint 
4763 g_child_watch_add (GPid            pid,
4764                    GChildWatchFunc function,
4765                    gpointer        data)
4766 {
4767   return g_child_watch_add_full (G_PRIORITY_DEFAULT, pid, function, data, NULL);
4768 }
4769
4770
4771 /* Idle functions */
4772
4773 static gboolean 
4774 g_idle_prepare  (GSource  *source,
4775                  gint     *timeout)
4776 {
4777   *timeout = 0;
4778
4779   return TRUE;
4780 }
4781
4782 static gboolean 
4783 g_idle_check    (GSource  *source)
4784 {
4785   return TRUE;
4786 }
4787
4788 static gboolean
4789 g_idle_dispatch (GSource    *source, 
4790                  GSourceFunc callback,
4791                  gpointer    user_data)
4792 {
4793   if (!callback)
4794     {
4795       g_warning ("Idle source dispatched without callback\n"
4796                  "You must call g_source_set_callback().");
4797       return FALSE;
4798     }
4799   
4800   return callback (user_data);
4801 }
4802
4803 /**
4804  * g_idle_source_new:
4805  * 
4806  * Creates a new idle source.
4807  *
4808  * The source will not initially be associated with any #GMainContext
4809  * and must be added to one with g_source_attach() before it will be
4810  * executed. Note that the default priority for idle sources is
4811  * %G_PRIORITY_DEFAULT_IDLE, as compared to other sources which
4812  * have a default priority of %G_PRIORITY_DEFAULT.
4813  * 
4814  * Return value: the newly-created idle source
4815  **/
4816 GSource *
4817 g_idle_source_new (void)
4818 {
4819   GSource *source;
4820
4821   source = g_source_new (&g_idle_funcs, sizeof (GSource));
4822   g_source_set_priority (source, G_PRIORITY_DEFAULT_IDLE);
4823
4824   return source;
4825 }
4826
4827 /**
4828  * g_idle_add_full:
4829  * @priority: the priority of the idle source. Typically this will be in the
4830  *            range between #G_PRIORITY_DEFAULT_IDLE and #G_PRIORITY_HIGH_IDLE.
4831  * @function: function to call
4832  * @data:     data to pass to @function
4833  * @notify:   function to call when the idle is removed, or %NULL
4834  * 
4835  * Adds a function to be called whenever there are no higher priority
4836  * events pending.  If the function returns %FALSE it is automatically
4837  * removed from the list of event sources and will not be called again.
4838  * 
4839  * This internally creates a main loop source using g_idle_source_new()
4840  * and attaches it to the main loop context using g_source_attach(). 
4841  * You can do these steps manually if you need greater control.
4842  * 
4843  * Return value: the ID (greater than 0) of the event source.
4844  * Rename to: g_idle_add
4845  **/
4846 guint 
4847 g_idle_add_full (gint           priority,
4848                  GSourceFunc    function,
4849                  gpointer       data,
4850                  GDestroyNotify notify)
4851 {
4852   GSource *source;
4853   guint id;
4854   
4855   g_return_val_if_fail (function != NULL, 0);
4856
4857   source = g_idle_source_new ();
4858
4859   if (priority != G_PRIORITY_DEFAULT_IDLE)
4860     g_source_set_priority (source, priority);
4861
4862   g_source_set_callback (source, function, data, notify);
4863   id = g_source_attach (source, NULL);
4864   g_source_unref (source);
4865
4866   return id;
4867 }
4868
4869 /**
4870  * g_idle_add:
4871  * @function: function to call 
4872  * @data: data to pass to @function.
4873  * 
4874  * Adds a function to be called whenever there are no higher priority
4875  * events pending to the default main loop. The function is given the
4876  * default idle priority, #G_PRIORITY_DEFAULT_IDLE.  If the function
4877  * returns %FALSE it is automatically removed from the list of event
4878  * sources and will not be called again.
4879  * 
4880  * This internally creates a main loop source using g_idle_source_new()
4881  * and attaches it to the main loop context using g_source_attach(). 
4882  * You can do these steps manually if you need greater control.
4883  * 
4884  * Return value: the ID (greater than 0) of the event source.
4885  **/
4886 guint 
4887 g_idle_add (GSourceFunc    function,
4888             gpointer       data)
4889 {
4890   return g_idle_add_full (G_PRIORITY_DEFAULT_IDLE, function, data, NULL);
4891 }
4892
4893 /**
4894  * g_idle_remove_by_data:
4895  * @data: the data for the idle source's callback.
4896  * 
4897  * Removes the idle function with the given data.
4898  * 
4899  * Return value: %TRUE if an idle source was found and removed.
4900  **/
4901 gboolean
4902 g_idle_remove_by_data (gpointer data)
4903 {
4904   return g_source_remove_by_funcs_user_data (&g_idle_funcs, data);
4905 }
4906
4907 /**
4908  * g_main_context_invoke:
4909  * @context: a #GMainContext, or %NULL
4910  * @function: function to call
4911  * @data: data to pass to @function
4912  *
4913  * Invokes a function in such a way that @context is owned during the
4914  * invocation of @function.
4915  *
4916  * If @context is %NULL then the global default main context — as
4917  * returned by g_main_context_default() — is used.
4918  *
4919  * If @context is owned by the current thread, @function is called
4920  * directly.  Otherwise, if @context is the thread-default main context
4921  * of the current thread and g_main_context_acquire() succeeds, then
4922  * @function is called and g_main_context_release() is called
4923  * afterwards.
4924  *
4925  * In any other case, an idle source is created to call @function and
4926  * that source is attached to @context (presumably to be run in another
4927  * thread).  The idle source is attached with #G_PRIORITY_DEFAULT
4928  * priority.  If you want a different priority, use
4929  * g_main_context_invoke_full().
4930  *
4931  * Note that, as with normal idle functions, @function should probably
4932  * return %FALSE.  If it returns %TRUE, it will be continuously run in a
4933  * loop (and may prevent this call from returning).
4934  *
4935  * Since: 2.28
4936  **/
4937 void
4938 g_main_context_invoke (GMainContext *context,
4939                        GSourceFunc   function,
4940                        gpointer      data)
4941 {
4942   g_main_context_invoke_full (context,
4943                               G_PRIORITY_DEFAULT,
4944                               function, data, NULL);
4945 }
4946
4947 /**
4948  * g_main_context_invoke_full:
4949  * @context: a #GMainContext, or %NULL
4950  * @priority: the priority at which to run @function
4951  * @function: function to call
4952  * @data: data to pass to @function
4953  * @notify: a function to call when @data is no longer in use, or %NULL.
4954  *
4955  * Invokes a function in such a way that @context is owned during the
4956  * invocation of @function.
4957  *
4958  * This function is the same as g_main_context_invoke() except that it
4959  * lets you specify the priority incase @function ends up being
4960  * scheduled as an idle and also lets you give a #GDestroyNotify for @data.
4961  *
4962  * @notify should not assume that it is called from any particular
4963  * thread or with any particular context acquired.
4964  *
4965  * Since: 2.28
4966  **/
4967 void
4968 g_main_context_invoke_full (GMainContext   *context,
4969                             gint            priority,
4970                             GSourceFunc     function,
4971                             gpointer        data,
4972                             GDestroyNotify  notify)
4973 {
4974   g_return_if_fail (function != NULL);
4975
4976   if (!context)
4977     context = g_main_context_default ();
4978
4979   if (g_main_context_is_owner (context))
4980     {
4981       while (function (data));
4982       if (notify != NULL)
4983         notify (data);
4984     }
4985
4986   else
4987     {
4988       GMainContext *thread_default;
4989
4990       thread_default = g_main_context_get_thread_default ();
4991
4992       if (!thread_default)
4993         thread_default = g_main_context_default ();
4994
4995       if (thread_default == context && g_main_context_acquire (context))
4996         {
4997           while (function (data));
4998
4999           g_main_context_release (context);
5000
5001           if (notify != NULL)
5002             notify (data);
5003         }
5004       else
5005         {
5006           GSource *source;
5007
5008           source = g_idle_source_new ();
5009           g_source_set_priority (source, priority);
5010           g_source_set_callback (source, function, data, notify);
5011           g_source_attach (source, context);
5012           g_source_unref (source);
5013         }
5014     }
5015 }